【发布时间】:2020-08-20 22:20:25
【问题描述】:
我正在开发 Chrome 扩展程序。
我尝试将inpage 脚本注入所有网页,我通过contentscript (https://developer.chrome.com/extensions/content_scripts) 注入它
这个inpage 脚本基本上会向扩展的后台脚本发送一些消息(https://developer.chrome.com/extensions/background_pages)
一些伪代码:
// contentscript.ts
// the bundled file of this source is executed in the website
const inpageContent = fs.readFileSync(
path.join(
__dirname,
'dist',
'js',
'inPage.bundle.js'
),
'utf8'
);
function injectScript(content: string) {
try {
const container = document.head || document.documentElement;
const scriptTag = document.createElement('script');
scriptTag.setAttribute('async', 'false');
scriptTag.textContent = content;
container.insertBefore(scriptTag, container.children[0]);
container.removeChild(scriptTag);
} catch (e) {
console.error('injection failed.', e);
}
}
injectScript(inpageContent)
export {};
// inpage.ts
// it injects `window.myextension` to the webpage
import { browser } from 'webextension-polyfill-ts';
declare global {
interface Window {
myextension: {
sendHelloWorld: () => void;
};
}
}
window.myextension = {
sendHelloWorld: () => {
browser.runtime.sendMessage({msg: 'helloworld'});
},
};
export {};
后台脚本只会注销收到的消息。
网络应用将能够调用window.myextension.sendHelloWorld()(或通过网络控制台)
问题在于fs 是一个节点函数。我基本上需要在构建时获取inpage.bundle.js 作为javascript 字符串常量。以便contentscript.bundle.js 在 webApp 中注入脚本。
有什么帮助吗?
【问题讨论】:
标签: javascript typescript webpack google-chrome-extension