This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.js
executable file
·43 lines (38 loc) · 1.6 KB
/
inject.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
function isInjected(tabId) {
return chrome.tabs.executeScriptAsync(tabId, {
code: `var injected = window.reactExampleInjected;
window.reactExampleInjected = true;
injected;`,
runAt: 'document_start'
});
}
function loadScript(name, tabId, cb) {
if (process.env.NODE_ENV === 'production') {
chrome.tabs.executeScript(tabId, { file: `/js/${name}.bundle.js`, runAt: 'document_end' }, cb);
} else {
// dev: async fetch bundle
fetch(`http://localhost:3000/js/${name}.bundle.js`)
.then(res => res.text())
.then((fetchRes) => {
// Load redux-devtools-extension inject bundle,
// because inject script and page is in a different context
const request = new XMLHttpRequest();
request.open('GET', 'chrome-extension://lmhkpmbekcpmknklioeibfkpmmfibljd/js/redux-devtools-extension.js'); // sync
request.send();
request.onload = () => {
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
chrome.tabs.executeScript(tabId, { code: request.responseText, runAt: 'document_start' });
}
};
chrome.tabs.executeScript(tabId, { code: fetchRes, runAt: 'document_end' }, cb);
});
}
}
const arrowURLs = ['^https://github\\.com'];
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (changeInfo.status !== 'loading' || !tab.url.match(arrowURLs.join('|'))) return;
const result = await isInjected(tabId);
if (chrome.runtime.lastError || result[0]) return;
// eslint-disable-next-line no-console
loadScript('inject', tabId, () => console.log('load inject bundle success!'));
});