【问题标题】:Webpack: Inject a bundled file in anotherWebpack:将捆绑的文件注入另一个
【发布时间】: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


    【解决方案1】:

    我最终捆绑了它,将其复制到源文件夹,然后使用raw-loader 导入捆绑的文件。

    参见。 https://stackoverflow.com/a/57156718/9510521

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2016-12-08
      • 2018-07-03
      相关资源
      最近更新 更多