<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?
import foo from "https://example.com/module.mjs"
import("https://example.com/module.mjs").then(console.log)
const myWorker = new Worker('worker.js')
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.
The integrity attribute allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated. Subresource Integrity (SRI) is a W3C specification that allows web developers to ensure that resources hosted on third-party servers have not been altered.
To use SRI, a website author wishing to include a resource from a third party can specify a cryptographic hash of the resource in addition to the location of the resource. Browsers fetching the resource can then compare the hash provided by the website author with the hash computed from the resource.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With