background.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Map tab IDs to connections
  2. const connections = new Map();
  3. // Listen for connections from the devtools panel
  4. chrome.runtime.onConnect.addListener(port => {
  5. let tabId;
  6. // Listen for messages from the devtools panel
  7. port.onMessage.addListener(message => {
  8. if (message.name === 'init') {
  9. tabId = message.tabId;
  10. connections.set(tabId, port);
  11. } else if ((message.name === 'traverse' || message.name === 'reload-scene') && tabId) {
  12. // Forward traverse or reload request to content script
  13. chrome.tabs.sendMessage(tabId, message);
  14. } else if (message.name === 'request-initial-state' && tabId) {
  15. chrome.tabs.sendMessage(tabId, message);
  16. } else if (tabId === undefined) {
  17. console.warn('Background: Message received from panel before init:', message);
  18. }
  19. });
  20. // Clean up when devtools is closed
  21. port.onDisconnect.addListener(() => {
  22. if (tabId) {
  23. connections.delete(tabId);
  24. }
  25. });
  26. });
  27. // Listen for messages from the content script
  28. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  29. if (sender.tab) {
  30. const tabId = sender.tab.id;
  31. const port = connections.get(tabId);
  32. if (port) {
  33. // Forward the message to the devtools panel
  34. try {
  35. port.postMessage(message);
  36. // Send immediate response to avoid "message channel closed" error
  37. sendResponse({ received: true });
  38. } catch (e) {
  39. console.error('Error posting message to devtools:', e);
  40. // If the port is broken, clean up the connection
  41. connections.delete(tabId);
  42. }
  43. }
  44. }
  45. return false; // Return false to indicate synchronous handling
  46. });
  47. // Listen for page navigation events
  48. chrome.webNavigation.onCommitted.addListener(details => {
  49. const { tabId, frameId } = details;
  50. const port = connections.get(tabId);
  51. if (port) {
  52. port.postMessage({
  53. id: 'three-devtools',
  54. type: 'committed',
  55. frameId: frameId
  56. });
  57. }
  58. });
粤ICP备19079148号