Mike Daines

Viz.js 3.21.0 added the option to pass a trusted type policy object created using the Trusted Types API to the renderSVGElement() convenience method.

If you specify a policy with the trustedTypePolicy option, the renderSVGElement() method will use it to sanitize SVG data before parsing.

Here’s an example using DOMPurify:

// Create the policy object:

const trustedTypePolicy = trustedTypes.createPolicy("purify", {
  createHTML(input) {
    return DOMPurify.sanitize(input, {
      RETURN_TRUSTED_TYPE: false
    });
  }
});

// When rendering:

const src = `graph { example[href="javascript:alert()"] }`;
const svgElement = viz.renderSVGElement(src, { trustedTypePolicy });

This ensures that the href attribute containing the alert() call is not present in svgElement.

It’s necessary to specify RETURN_TRUSTED_TYPE because the createHTML() function should return a string, not a TrustedHTML value.