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:
Example:
(async () => { const src = chrome.runtime.getURL("your/content_main.js"); const contentMain = await import(src); contentMain.main(); })();
Synchronous "import" workaround for normal non-module scripts:
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!