<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
<script id="myScript" href="script.js"></script>
</svg>SVGScriptElement: href property / notebook
SVGScriptElement: href property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const scriptElement = document.getElementById("myScript");
// Access the href property
console.log(scriptElement.href.baseVal); // Output: "script.js"if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };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
},
});<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
<script id="aScriptElement" href="example.js"></script>
</svg>// Get the script element we're injecting the URL into
const scriptElement = document.getElementById("aScriptElement");// The potentially malicious string
// We won't be including untrustedScript 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)
scriptElement.href.baseVal = trustedScriptURL;