Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-11-24 12:00:19
Original
237 people have browsed it

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

Importing ES6 Modules in Content Scripts for Chrome Extensions

Problem:

When attempting to import ES6 modules in a Chrome extension content script using standard import/export syntax, error messages are encountered.

Context:

Chrome 61 introduced support for JavaScript modules, but the import syntax is not recognized in content scripts of Chrome extensions.

Solution: Asynchronous Dynamic import() Function

To import ES6 modules in Chrome extension content scripts, use the asynchronous dynamic import() function:

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

Additional Considerations:

  • Declare imported scripts in the extension's manifest as web accessible resources.
  • This approach relies on an asynchronous function, which could potentially be blocked by a website's service worker.

Synchronous "import" Workaround

As an alternative, use a normal non-module script and add its name to the "js" array in "content_scripts" before the main content script. Global variables and functions from the script can be accessed directly.

The above is the detailed content of How Can I 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