In Chrome 61, support for JavaScript modules was added. Now I'm running Chrome 63.
I'm trying to use a module in a Chrome extension content script using the import
/export
syntax.
Inmanifest.json
:
"content_scripts": [ { "js": [ "content.js" ], } ]
Inmy-script.js
(with content.js
same directory):
'use strict'; const injectFunction = () => window.alert('hello world'); export default injectFunction;
Incontent.js
:
'use strict'; import injectFunction from './my-script.js'; injectFunction();
I get this error:Uncaught syntax error: Unexpected identifier
If I change the import syntax to import {injectFunction} from './my-script.js';
I get this error: Uncaught SyntaxError: Unexpected token {
< /p>
Is there a problem using this syntax in content.js
in the Chrome extension (because in HTML you have to use < ;code>
Usedynamic
import()
function.Unlike the unsafe workaround using
elements, this workaround runs in the same secure JS environment (isolated world of content scripts) and your imported modules can still access global variables As well as functions for the initial content script, including the built-in
chrome
API, such aschrome.runtime.sendMessage
.In
content_script.js
it looks likeYou also need to declare the imported script in the manifest'sWeb Accessible Resources:
// ManifestV3
// ManifestV2
Learn more details:
chrome.runtime.getURL
李>Hope it helps.
Disclaimer
First, it’s important to note that as of January 2018, content scripts do not support modules. This workaround works around the restriction to your extension by embedding the module
script
tag into the returned page.This is an unsafe solution!
Web scripts (or other extensions) can exploit your code and extract/spoof data by using setters/getters, proxies on
Object.prototype
and other prototypesfunctions and /or the global object, because the code inside thescript
element runs in the JS context of the page, rather than in the secure isolated JS environment that runs content scripts by default.A safe workaround isthe dynamicimport()
shown in another answer
here.Solution
This is my
manifest.json
:Please note that I have two scripts in
web_accessible_resources
.This is my
content.js
:This will insert
main.js
as a module script into the web page.All my business logic is now in
main.js
.For this method to work,
main.js
(and all the scripts Iimport
into)mustbe located in web_accessible_resources in themanifest
.Usage example:
my-script.js
In
main.js
, this is an example of the import script:This works! No errors were thrown and I was happy. :)