-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.js
31 lines (27 loc) · 1.04 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
import { injectPaths } from '../../../config';
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) => {
chrome.tabs.executeScript(tabId, { code: fetchRes, runAt: 'document_end' }, cb);
});
}
}
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (changeInfo.status !== 'loading' || !tab.url.match(injectPaths.join('|'))) return;
const result = await isInjected(tabId);
if (chrome.runtime.lastError || result[0]) return;
loadScript('inject', tabId, () => console.log('load inject bundle success!'));
});