Home > Web Front-end > JS Tutorial > How Can I Load ES6 Modules in My Chrome Extension\'s Content Script?

How Can I Load ES6 Modules in My Chrome Extension\'s Content Script?

DDD
Release: 2024-11-25 11:55:18
Original
319 people have browsed it

How Can I Load ES6 Modules in My Chrome Extension's Content Script?

Loading ES6 Modules in a Content Script for Chrome Extension

Background:
Chrome 61 introduced support for JavaScript modules. However, loading modules in a content script for Chrome extensions can be challenging due to the limitations of the content script environment.

Issue:
You are attempting to use import/export syntax in a content script, but encounter syntax errors.

Solution:
There are two approaches to loading modules in a content script:

Asynchronous dynamic import() function for ES modules:

  • Declare the script to be loaded in the extension's manifest as a Web Accessible Resource.
  • Use the import() function within the content script to dynamically import the module during runtime.

Example:

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

Synchronous "import" workaround for normal non-module scripts:

  • Write the module as a normal non-module script.
  • Add its name to the "js" array in the "content_scripts" section of the manifest, before the main content script.
  • Access the module's variables and functions directly in the content script.

Note:
The asynchronous dynamic import approach is safer and more flexible, but may be blocked by the website's service worker. The synchronous "import" workaround is less robust but may be more reliable.

The above is the detailed content of How Can I Load ES6 Modules in My Chrome Extension\'s Content Script?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template