background.js 1.6 KB

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