sinanbekar / browser-extension-react-typescript-starter

🚀 React & TypeScript Starter for developing web extensions with hot reload!
MIT License
121 stars 20 forks source link

How can I add script.js? #49

Closed katopz closed 2 years ago

katopz commented 2 years ago

Usually in vanilla js I use content_script.js that will inject script.js to the page but I can't find any example related to that?

const container = document.head || document.documentElement
const scriptTag = document.createElement('script')
scriptTag.setAttribute('async', 'false')
scriptTag.src = chrome.runtime.getURL('script.js')
container.insertBefore(scriptTag, container.children[0])
container.removeChild(scriptTag)

Second question is where to place that script.ts to trigger script.js build and include it in HMR?

sinanbekar commented 2 years ago

Thank you for reaching out. I am sharing an example setup that I created for one of my clients. You can create the main injection script in content/injection folder. (or wherever you want to structure it, crxjs and vite handle it. see: https://github.com/crxjs/chrome-extension-tools) And you can import it inside content/index.ts

import pageContextInject from './injection/pageContextInject?script&module';
const setupInjectPageContextScript = () => {
  const s = document.createElement('script');
  s.src = chrome.runtime.getURL(pageContextInject);
  s.type = 'module';
  document.head.appendChild(s);
  s.onload = function () {
    s.remove();
  };
};

And at the end

(async function initialize() {
  const config = await getExtensionConfig();
  if (config.enabled) {
    //setupInitialDispatch();
    setupInjectPageContextScript();
    //setupInjections();
    //setupSomeOther();
  }
})();

Hope you find it useful.

sinanbekar commented 2 years ago

@katopz you may need to add this code to typings.d.ts to make tsc happy. see: https://www.typescriptlang.org/docs/handbook/modules.html#wildcard-module-declarations https://vitejs.dev/guide/assets.html#importing-asset-as-url

declare module '*?script&module' {
  const src: string;
  export default src;
}
katopz commented 2 years ago

Wow that's a super fancy things to do for inject something. 😆

Thanks!