1
0

content-script.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* global chrome */
  2. // Constants
  3. const MESSAGE_ID = 'three-devtools';
  4. const MESSAGE_REQUEST_STATE = 'request-state';
  5. const MESSAGE_REQUEST_OBJECT_DETAILS = 'request-object-details';
  6. const MESSAGE_SCROLL_TO_CANVAS = 'scroll-to-canvas';
  7. const MESSAGE_HIGHLIGHT_OBJECT = 'highlight-object';
  8. const MESSAGE_UNHIGHLIGHT_OBJECT = 'unhighlight-object';
  9. // Helper to check if extension context is valid
  10. function isExtensionContextValid() {
  11. try {
  12. chrome.runtime.getURL( '' );
  13. return true;
  14. } catch ( error ) {
  15. return false;
  16. }
  17. }
  18. // Unified message handler for window messages
  19. function handleWindowMessage( event ) {
  20. // Only accept messages with the correct id
  21. if ( ! event.data || event.data.id !== MESSAGE_ID ) return;
  22. // Determine source: 'main' for window, 'iframe' otherwise
  23. const source = event.source === window ? 'main' : 'iframe';
  24. if ( ! isExtensionContextValid() ) {
  25. console.warn( 'Extension context invalidated, cannot send message' );
  26. return;
  27. }
  28. event.data.source = source;
  29. chrome.runtime.sendMessage( event.data );
  30. }
  31. // Listener for messages from the background script (originating from panel)
  32. function handleBackgroundMessage( message ) {
  33. const forwardableMessages = new Set( [
  34. MESSAGE_REQUEST_STATE,
  35. MESSAGE_REQUEST_OBJECT_DETAILS,
  36. MESSAGE_SCROLL_TO_CANVAS,
  37. MESSAGE_HIGHLIGHT_OBJECT,
  38. MESSAGE_UNHIGHLIGHT_OBJECT
  39. ] );
  40. if ( forwardableMessages.has( message.name ) ) {
  41. message.id = MESSAGE_ID;
  42. window.postMessage( message, '*' );
  43. }
  44. }
  45. // Add event listeners
  46. window.addEventListener( 'message', handleWindowMessage, false );
  47. chrome.runtime.onMessage.addListener( handleBackgroundMessage );
  48. // Icon color scheme
  49. const isLightTheme = window.matchMedia( '(prefers-color-scheme: light)' ).matches;
  50. chrome.runtime.sendMessage( { scheme: isLightTheme ? 'light' : 'dark' } );
  51. window.matchMedia( '(prefers-color-scheme: light)' ).onchange = event => {
  52. chrome.runtime.sendMessage( { scheme: event.matches ? 'light' : 'dark' } );
  53. };
粤ICP备19079148号