Import JS file from within an injected JS

151 Views Asked by At

I have some "greases" (JS/CSS adaptations) which I inject by an addon into pages of a certain domain. Now my colleagues want to use them, too. In order to deploy changes and updates on this adaptations dynamically I've published a CSS and a JavaScript file which I want to import from within the addon.

This works fine with the CSS (@import url('https://contoso.com/ownstyle.css')), but the JS import import from 'https://contoso.com/ownscript.js) only results in "SyntaxError: Cannot use import statement outside a module".

I was consulting this ES6: import module from URL but the solution here demands a tagged import from within the page. Is there a way to import it from within the addons injected JS?

1

There are 1 best solutions below

1
The Bomb Squad On

Okay, so to import a script there's the 3 line function below and an example usage

Does this work to accomplish your goal?

async function require(url){
  let module={exports:{}}, {exports}=module
  eval( await(await fetch(url)).text() )
  return module.exports
}
let url="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.4/d3.min.js";
require(url)
.then(result=>{
  console.log(Object.keys(result))
  //do things with resultant export
})