Microsoft Clarity has introduced support for custom Trusted Types policies, enhancing security by allowing developers to specify their own policies for handling content within applications. Trusted Types is a browser-enforced feature designed to prevent cross-site scripting (XSS) attacks by restricting dangerous web APIs and requiring content to pass through trusted policies before execution.
What Are Trusted Types Policies?
Trusted Types help mitigate malicious code execution by enforcing that any content passed to sensitive web APIs is sanitized and validated through predefined policies.
Custom Trusted Types in Microsoft Clarity
Previously, Clarity supported only a default Trusted Types policy. Now, developers can specify a custom policy by adding an optional parameter to the Clarity tag request in the setup code:
https://www.clarity.ms/tag/<ProjectId>?trustedTypes=<PolicyName>
This update allows tailored security policies suited to specific application needs.
Benefits of Custom Trusted Types
- Enhanced Security: Ensures only sanitized and validated content executes, reducing XSS risks.
- Flexibility: Allows different handling for various content types like HTML, scripts, and URLs.
- Compliance: Helps meet stringent security standards and best practices.
How to Set Up Custom Trusted Types
- Create a Trusted Types Policy using
trustedTypes.createPolicy()
. Example:
const ClarityPolicy = trustedTypes.createPolicy('ClarityPolicy', {
createScriptURL: (input) => {
if (input.startsWith('https://www.clarity.ms')) {
return input;
}
throw new Error('Untrusted URL');
}
});
- Update the Clarity Tag by adding the
trustedTypes
parameter:
<script type="text/javascript">
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i+"?trustedTypes=ClarityPolicy";
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "<ProjectId>");
</script>
If the browser does not support Trusted Types, the script falls back to its default behavior.
Conclusion
The addition of custom Trusted Types policies in Microsoft Clarity offers developers improved security without sacrificing functionality. This feature supports compliance, scalability, and best-in-class web security, giving developers greater control over frontend security while integrating session recording and analytics.
For more technical details, developers can refer to MDN’s Trusted Types documentation.