background.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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号