簡體   English   中英

Webpack:將捆綁的文件注入另一個

[英]Webpack: Inject a bundled file in another

我正在開發一個 Chrome 擴展程序。

我嘗試將頁內腳本注入所有網頁,我通過contentscriptinpage ://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導入捆綁的文件。

參看。 https://stackoverflow.com/a/57156718/9510521

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM