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(); })();
Additional Considerations:
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!