if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };HTMLScriptElement: src property / notebook
HTMLScriptElement: src property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const scriptAllowList = [
// Some list of allowed URLs
];
const policy = trustedTypes.createPolicy("script-url-policy", {
createScriptURL(input) {
if (scriptAllowList.includes(input)) {
return input; // allow the script
}
console.log(`Script not in scriptAllowList: ${input}`);
return ""; // Block the script
},
});<script id="el"></script>// Get the script element we're injecting the code into
const el = document.getElementById("el");// The potentially malicious string
// We won't be including untrustedScriptURL in our scriptAllowList array
const untrustedScriptURL = "https://evil.example.com/naughty.js";
// Create a TrustedScriptURL instance using the policy
const trustedScriptURL = policy.createScriptURL(untrustedScriptURL);
// Inject the TrustedScriptURL (which contains a trusted URL)
el.src = trustedScriptURL;<script id="script-with-src" type="module" src="/main.js"></script>
<script id="script-without-src" type="module"></script>const scriptWithSrc = document.getElementById("script-with-src");
console.log(scriptWithSrc.src); // Output: "https://example.com/main.js"
const scriptWithoutSrc = document.getElementById("script-without-src");
console.log(scriptWithoutSrc.src); // Output: ""