-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
injector.js
43 lines (38 loc) · 1.48 KB
/
injector.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
console.log(`injector.js is running`);
// inject script into javascript context of tab
const injectedScript = document.createElement('script');
injectedScript.src = chrome.runtime.getURL('injected.js');
injectedScript.onload = function () {
this.remove();
};
(document.head || document.documentElement).appendChild(injectedScript);
let comms;
const sendToFrontEnd = (messageHead, messageBody) => {
if (comms) {
comms.postMessage({messageHead, messageBody});
return true;
} else {
return false;
}
};
// set up listener to listen for messages from injected script
window.addEventListener('message', (e) => {
if (e.data && e.data.deValtioMessage) {
const [messageHead, messageBody] = e.data.deValtioMessage;
console.log(`Received message from injected. Sending ${messageHead} front end with payload: ${JSON.stringify(messageBody)}`)
messageSender = setInterval( () => {
let messageSent = sendToFrontEnd(messageHead, messageBody);
if (messageSent) {
clearInterval(messageSender);
messageSender = null;
} else {
console.log(`Message sending from content script to front end failed. messageHead is: ${messageHead}`);
}
}, 1000);
};
});
// creates connection between extension and content script
chrome.runtime.onConnect.addListener(port => {
console.log('Content script is now connected to the Front End', port);
comms = port;
});