"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to successfully import ES6 modules in Chrome extension content script?

How to successfully import ES6 modules in Chrome extension content script?

Posted on 2025-04-12
Browse:249

How Can I Successfully Import ES6 Modules into My Chrome Extension\'s Content Scripts?

Importing ES6 Modules in Chrome Extension Content Scripts

Issue: In Chrome 63, importing ES6 modules using the import/export syntax in a content script results in syntax errors.

Solution:

Chrome extensions support ES6 modules through an asynchronous dynamic import() function:

(async () => {
  const src = chrome.runtime.getURL("your/content_main.js");
  const contentMain = await import(src);
  contentMain.main();
})();

However, this method has limitations:

  • It can be blocked by the website's service worker.
  • Declaring the imported scripts in manifest's Web Accessible Resources is required.

For non-module scripts, consider:

  • Using a normal non-module script.
  • Adding its name to "js" in "content_scripts" before your main content script.
  • Using the global variables/functions directly.

Additional Information:

  • [How to use ES6 “import” with Chrome Extension](https://stackoverflow.com/a/50132415)
  • [Working Example of ES6 import in Chrome Extension](https://github.com/browsers-toolbox/es-import-in-extension)
  • [chrome.runtime.getURL](https://developer.chrome.com/extensions/runtime#method-getURL)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3