简体   繁体   中英

Webpack: Inject a bundled file in another

I am developing a Chrome Extension.

I try to make inject an inpage script into all the webpages, I inject it via contentscript ( https://developer.chrome.com/extensions/content_scripts )

This inpage script will basically send some message to background scripts of the extension ( https://developer.chrome.com/extensions/background_pages )

Some pseudo-code:

// 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 {};

background script will just log out the message received.

the web-app would be able to call window.myextension.sendHelloWorld() (or via the web console)

The issue is that fs is a node function. I basically need to fetch the inpage.bundle.js as a javascript string constant at build time. so that contentscript.bundle.js inject the script within the webApp.

Any help on that?

I ended up bundling it, copying it to the source folder, then use raw-loader to import the bundled file.

cf. https://stackoverflow.com/a/57156718/9510521

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM