-
Notifications
You must be signed in to change notification settings - Fork 45.6k
/
contentScript.js
97 lines (83 loc) · 2.22 KB
/
contentScript.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* global chrome */
'use strict';
let backendDisconnected: boolean = false;
let backendInitialized: boolean = false;
function sayHelloToBackend() {
window.postMessage(
{
source: 'react-devtools-content-script',
hello: true,
},
'*',
);
}
function handleMessageFromDevtools(message) {
window.postMessage(
{
source: 'react-devtools-content-script',
payload: message,
},
'*',
);
}
function handleMessageFromPage(evt) {
if (
evt.source === window &&
evt.data &&
evt.data.source === 'react-devtools-bridge'
) {
backendInitialized = true;
port.postMessage(evt.data.payload);
}
}
function handleDisconnect() {
backendDisconnected = true;
window.removeEventListener('message', handleMessageFromPage);
window.postMessage(
{
source: 'react-devtools-content-script',
payload: {
type: 'event',
event: 'shutdown',
},
},
'*',
);
}
// proxy from main page to devtools (via the background page)
const port = chrome.runtime.connect({
name: 'content-script',
});
port.onMessage.addListener(handleMessageFromDevtools);
port.onDisconnect.addListener(handleDisconnect);
window.addEventListener('message', handleMessageFromPage);
sayHelloToBackend();
// The backend waits to install the global hook until notified by the content script.
// In the event of a page reload, the content script might be loaded before the backend is injected.
// Because of this we need to poll the backend until it has been initialized.
if (!backendInitialized) {
const intervalID = setInterval(() => {
if (backendInitialized || backendDisconnected) {
clearInterval(intervalID);
} else {
sayHelloToBackend();
}
}, 500);
}
// listen message coming from background script
chrome.runtime.onMessage.addListener(request => {
// If the message is related to hotkeys / command being triggered
if (request.command) {
// Pass hotkeys / command to page scripts since hotkeys is usually have something to do with the devtools itself
window.postMessage(
{
source: 'react-devtools-content-script',
payload: {
type: 'command',
command: request.command,
},
},
'*',
);
}
});