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

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

Barbara Streisand
Release: 2024-11-27 11:36:19
Original
786 people have browsed it

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

Importing ES6 Modules in Chrome Extension Content Scripts

Problem:

In Chrome 63, importing ES6 modules using import/export syntax in content scripts results in SyntaxErrors.

Cause:

Unlike HTML scripts, content scripts do not natively support module loading.

Solution: Asynchronous dynamic import() function

To resolve this issue, use the following workaround:

  1. In manifest.json, declare your module script as a web accessible resource.
  2. In content_script.js, use the import() function to asynchronously load your module.
  3. Await the import and run the main function of your module.

Example:

manifest.json:

{
  "web_accessible_resources": [
    {
      "matches": ["<all_urls>"],
      "resources": ["my-module.js"]
    }
  ],
  ...
}
Copy after login

content_script.js:

(async () => {
  const src = chrome.runtime.getURL("my-module.js");
  const module = await import(src);
  module.main();
})();
Copy after login

Synchronous Import Workaround

Alternatively, you can use a synchronous import workaround for non-module scripts:

  1. Add the script to the "js" array in manifest.json.
  2. Reference the script's global variables and functions directly in your main content script.

The above is the detailed content of How Can I Import ES6 Modules into Chrome Extension 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