How to import ES6 modules in content script for Chrome Extension
I managed to find a workaround.
Disclaimer
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.
Workaround
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.
Example Usage: 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. :)
script for both modules and non-module usage - JavaScript
In the end, I set up two git branches:
1 - In the first one, I just kept the file without the "export", so no ES6 modules capabilities
2 - This other branch, I decided to set it up to be published on NPM, and in this one I exported my classes. If you use NPM for your development, it's already very probable that you also have a bundler like webpack to keep track of modules and dependencies.
Whenever I do a change, I do it in the master (no exports) branch, and then I merge the changes in the npm branch, to avoid writing the same code twice
Related Topics
Is the Promise Constructor Callback Executed Asynchronously
How to Return Values from Async Functions Using Async-Await from Function
Variable Scope in D3 JavaScript
How to Overload Functions in JavaScript
Differencebetween Bower and Npm
How to Prevent Form from Submitting Multiple Times from Client Side
Uncaught Typeerror: Illegal Invocation in JavaScript
How to Delay a Function Call for 5 Seconds
How to Destructure into Dynamically Named Variables in Es6
How to Measure a Time Spent on a Page
Pass Data or Modify Extension HTML in a New Tab/Window
How Does Variable Assignment Work in JavaScript
My Very Simple Greasemonkey Script Is Not Running
How to 'Minify' JavaScript Code
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
What Is This JavaScript Pattern Called and Why Is It Used
How to Access Local Scope Dynamically in JavaScript
How to Perform Case-Insensitive Sorting Array of String in JavaScript