Subresource integrity for es6 import or worker

2.2k views Asked by At

<script> accept integrity attribute, so I can load a module safely:

<script type="module"
  src="https://example.com/module.mjs"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"
></script>

But how to keep safe when loading module inside script?

  • with import:
import foo from "https://example.com/module.mjs"
  • dynamic import:
import("https://example.com/module.mjs").then(console.log)
  • or even web worker:
const myWorker = new Worker('worker.js')
1

There are 1 answers

0
Mayank Kumar Chaudhari On

Please see this question

Is it possible to use subresource integrity with ES6 module imports?

You can use RequireJS, and transpile your code to AMD or UMD to achieve this. RequireJS has a hook onNodeCreated, which gives you access to the script tag before it is added to document. You can add the sri attribute onto the script tag:

onNodeCreated: function(node, config, module, path) { node.setAttribute('integrity', integrityForModule); node.setAttribute('crossorigin', 'anonymous'); }

credit: https://stackoverflow.com/a/37065379

I use Webpack (with a target of UMD) and RequireJS. With the relevant modules put in the external section of the webpack configuration file, so the modules are not compiled into the transpiled code.