[英]Webpack: Inject a bundled file in another
我正在開發一個 Chrome 擴展程序。
我嘗試將頁內腳本注入所有網頁,我通過contentscript
( inpage
://developer.chrome.com/extensions/content_scripts )注入它
這個頁面內腳本基本上會向擴展的后台腳本發送一些消息( inpage
://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()
(或通過 web 控制台)
問題是fs
是一個節點 function。 我基本上需要在構建時將inpage.bundle.js
作為 javascript 字符串常量獲取。 以便contentscript.bundle.js
在 webApp 中注入腳本。
有什么幫助嗎?
我最終捆綁了它,將其復制到源文件夾,然后使用raw-loader
導入捆綁的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.