In Chrome 61, support for modules in JavaScript was added. Right now I am running Chrome 63.
I am trying to use import
/export
syntax in Chrome extension content script to use modules.
In manifest.json
:
"content_scripts": [
{
"js": [
"content.js"
],
}
]
In my-script.js
(same directory as content.js
):
'use strict';
const injectFunction = () => window.alert('hello world');
export default injectFunction;
In content.js
:
'use strict';
import injectFunction from './my-script.js';
injectFunction();
I receive this error: Uncaught SyntaxError: Unexpected identifier
If I change the import syntax to import {injectFunction} from './my-script.js';
I get this error: Uncaught SyntaxError: Unexpected token {
Is there some issue with using this syntax in content.js
in Chrome extension (since in HTML you have to use <script type="module" src="script.js">
syntax), or am I doing something wrong? It seems strange that Google would ignore support for extensions.
First of all, it’s important to say that content scripts don’t support modules as of January 2018. This workaround sidesteps the limitation by embedding module script
tag into the page that leads back to your extension.
A web page script (or another extension) can exploit your code and extract/spoof the data by using setters/getters on Object.prototype
and other prototypes, proxying functions and/or global objects, because the code inside a script
element runs in the JS context of the page, not in the safe isolated JS environment where content scripts run by default.
A safe workaround is the dynamic import()
shown in another answer here.
This is my manifest.json
:
"content_scripts": [ {
"js": [
"content.js"
]
}],
"web_accessible_resources": [
"main.js",
"my-script.js"
]
Note that I have two scripts in web_accessible_resources
.
This is my content.js
:
'use strict';
const script = document.createElement('script');
script.setAttribute("type", "module");
script.setAttribute("src", chrome.extension.getURL('main.js'));
const head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
head.insertBefore(script, head.lastChild);
This will insert main.js
into the webpage as a module script.
All my business logic is now in main.js
.
For this method to work, main.js
(as well as all scripts that I will import
) must be in web_accessible_resources
in the manifest.
my-script.js
'use strict';
const injectFunction = () => window.alert('hello world');
export {injectFunction};
And in main.js
this is an example of importing the script:
'use strict';
import {injectFunction} from './my-script.js';
injectFunction();
This works! No errors are thrown, and I am happy. :)