MDN self-hosted library · e01.org

SVGScriptElement: href property

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
  <script id="myScript" href="script.js"></script>
</svg>
js
const scriptElement = document.getElementById("myScript");

// Access the href property
console.log(scriptElement.href.baseVal); // Output: "script.js"
js
if (typeof trustedTypes === "undefined")
  trustedTypes = { createPolicy: (n, rules) => rules };
js
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
  },
});
html
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">
  <script id="aScriptElement" href="example.js"></script>
</svg>
js
// Get the script element we're injecting the URL into
const scriptElement = document.getElementById("aScriptElement");
js
// 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;