Using ES module in Chrome browser extension content script

Background

I am trying to include an UI library from others into browser extension’s content script (which would run on the target page)

Failures encountered

1. Getting Content Security Policy violation

As content script is used at target page, so including the script from https://unpkg.com would likely violate the target page policy. Tried to include the content_security_policy in the manifest.json, but just does not see any difference in behavior, so I suspect the manifest.json’s policy only affect background script (or maybe pop up scripts), but not content script.

2. Copy the script locally, inject it through creating script element and inject

The idea as following:

const scriptElem = document.createElement("script");scriptElem.src = chrome.runtime.getURL("/js/copied_es_module.js");scriptElem.type = "module";document.head.appendChild(scriptElem);sciptElem.addEventListener("load", action);function action(e) {  // code using the module...}
root[“XXX”] = factory();

2. What does work — put the local “copied_es_module.js” before the actual content script in manifest.json in the content_scripts[“js”] array

Just like this below, and I believe it just got load, and I don’t even need to create a script element to inject the module.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store