-
-
Notifications
You must be signed in to change notification settings - Fork 36.4k
Expand file tree
/
Copy pathcontent-script.js
More file actions
80 lines (53 loc) · 1.94 KB
/
content-script.js
File metadata and controls
80 lines (53 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* global chrome */
// Constants
const MESSAGE_ID = 'three-devtools';
const MESSAGE_REQUEST_STATE = 'request-state';
const MESSAGE_REQUEST_OBJECT_DETAILS = 'request-object-details';
const MESSAGE_SCROLL_TO_CANVAS = 'scroll-to-canvas';
const MESSAGE_HIGHLIGHT_OBJECT = 'highlight-object';
const MESSAGE_UNHIGHLIGHT_OBJECT = 'unhighlight-object';
// Helper to check if extension context is valid
function isExtensionContextValid() {
try {
chrome.runtime.getURL( '' );
return true;
} catch ( error ) {
return false;
}
}
// Unified message handler for window messages
function handleWindowMessage( event ) {
// Only accept messages with the correct id
if ( ! event.data || event.data.id !== MESSAGE_ID ) return;
// Determine source: 'main' for window, 'iframe' otherwise
const source = event.source === window ? 'main' : 'iframe';
if ( ! isExtensionContextValid() ) {
console.warn( 'Extension context invalidated, cannot send message' );
return;
}
event.data.source = source;
chrome.runtime.sendMessage( event.data );
}
// Listener for messages from the background script (originating from panel)
function handleBackgroundMessage( message ) {
const forwardableMessages = new Set( [
MESSAGE_REQUEST_STATE,
MESSAGE_REQUEST_OBJECT_DETAILS,
MESSAGE_SCROLL_TO_CANVAS,
MESSAGE_HIGHLIGHT_OBJECT,
MESSAGE_UNHIGHLIGHT_OBJECT
] );
if ( forwardableMessages.has( message.name ) ) {
message.id = MESSAGE_ID;
window.postMessage( message, '*' );
}
}
// Add event listeners
window.addEventListener( 'message', handleWindowMessage, false );
chrome.runtime.onMessage.addListener( handleBackgroundMessage );
// Icon color scheme
const isLightTheme = window.matchMedia( '(prefers-color-scheme: light)' ).matches;
chrome.runtime.sendMessage( { scheme: isLightTheme ? 'light' : 'dark' } );
window.matchMedia( '(prefers-color-scheme: light)' ).onchange = event => {
chrome.runtime.sendMessage( { scheme: event.matches ? 'light' : 'dark' } );
};