0

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?

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.