abhijithvijayan / web-extension-starter

🖥🔋Web Extension starter to build "Write Once Run on Any Browser" extension
MIT License
2.01k stars 171 forks source link

What could be right way to dynamically import a file from a npm package into a webpage through content_script? #44

Closed abhinavzspace closed 4 years ago

abhinavzspace commented 4 years ago

I have been unsuccessful in trying to import a file from npm package into a web page through content_script. I want to import this file on an action from popup browser action.

To establish the basic setup, I tried importing your emoji-log library. I followed the following steps:

  1. Add new CopyWebpackPlugin([{from: 'node_modules/emoji-log/lib/index.js', to: 'js/emoji-log/lib/index.js'}]), in webpack.config.js
  2. Add following in manifest.json.
    "web_accessible_resources": [
    "js/emoji-log/lib/index.js"
    ],
  3. In content script. (Right now for testing purpose, I am opening it directly. Otherwise I want to open it on an action)
    import browser from 'webextension-polyfill';
    (async () => {
    const src = browser.extension.getURL("js/emoji-log/lib/index.js");
    await import(src);
    })();

I get the following error:

Uncaught (in promise) Error: Cannot find module 'chrome-extension://bkglmbblddekhjgldmkjgadhojbhakjg/js/emoji-log/lib/index.js'

And strangely when I click on the filename, it opens up in the new tab straight away.

What am I missing here? I am stuck on this from quite a few hours.

(These instructions are mostly from here and here)

abhijithvijayan commented 4 years ago

Could you kindly add a reproducible repo for me to test the above?

abhinavzspace commented 4 years ago

Sure. Give me a few minutes. And Thanks!

abhijithvijayan commented 4 years ago

Try with browser.runtime.getURL()

abhinavzspace commented 4 years ago

Tried both. runtime and extension.

Please find the code here

abhijithvijayan commented 4 years ago

The path is generated correctly but the import statement seems to break the injected script usage

I will look more into it anyways. Also, even if this works in chrome, it won't work in firefox

abhinavzspace commented 4 years ago

ahhh... Is there an alternate way of doing this. I just need to inject script occasionally on an action.

abhijithvijayan commented 4 years ago

@abhinavzspace I had luck with this but it doesn't use dynamic imports.

I will look into this issue anyways. My guess with with babel plugins.

abhinavzspace commented 4 years ago

Thanks! Will look into it.

abhinavzspace commented 4 years ago

Confirmed. Alternate way you suggested, works. Thanks a lot.

abhijithvijayan commented 4 years ago

Cool. The way with dynamic import should've worked, but at this point I am unclear about why it doesn't work.

Closing this issue for now. Feel free to reopen if you run into problems again.

Thanks