Home > Web Front-end > JS Tutorial > How Can I Successfully Import ES6 Modules into My Chrome Extension\'s Content Scripts?

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

Linda Hamilton
Release: 2024-12-23 09:23:15
Original
697 people have browsed it

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();
})();
Copy after login

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)

The above is the detailed content of How Can I Successfully Import ES6 Modules into My Chrome Extension\'s Content Scripts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template