No Login Data Private Local Save

Trusted Types API Demo - Online Prevent XSS

19
0
0
0

Trusted Types API Demo

Online XSS Prevention Sandbox & Security Playground

Detecting...
"> Mouse Events
Controls which HTML elements & attributes survive sanitization
HTML / Payload Input Potentially Unsafe
Unsafe (Raw innerHTML)
Vulnerable
Safe (Trusted Types)
Sanitized
Generated Trusted Types Code Copy & Use
// Your Trusted Types implementation code will appear here...
// Select a payload and policy level, then click "Generate" or type in the editor
0
Dangerous constructs detected
0
Elements / Attributes sanitized
100%
Safe output confidence
Frequently Asked Questions

Trusted Types is a browser security API designed to eliminate DOM-based Cross-Site Scripting (XSS) attacks. It enforces that only trusted, sanitized data can be assigned to dangerous DOM sinks like innerHTML, outerHTML, document.write, and eval.

Instead of accepting arbitrary strings, these sinks require special typed objects — TrustedHTML, TrustedScript, or TrustedScriptURL — that can only be created through explicitly defined policies. This makes it impossible for attacker-controlled strings to reach execution contexts.

Trusted Types prevents XSS by enforcing a type-based security boundary:

  1. Default deny: All DOM sinks reject plain strings by default when Trusted Types are enforced via CSP.
  2. Policy enforcement: Developers must create explicit policies that validate or sanitize data before it reaches a sink.
  3. Audit trail: Each policy call is recorded, making it easy to audit where trusted values are created.
  4. Compile-time safety: TypeScript definitions help catch violations at development time.

For example, element.innerHTML = untrustedString will throw a TypeError when Trusted Types are enforced, forcing developers to use policy.createHTML(sanitizedString) instead.

As of 2024-2025, Trusted Types is supported in:

  • Google Chrome 83+ (full support)
  • Microsoft Edge 83+ (full support, Chromium-based)
  • Opera 69+ (Chromium-based)
  • Samsung Internet 14+
  • Firefox — Partial support in development (tracked in Bug 1709390)
  • Safari — Not yet supported (as of early 2025)

You can use feature detection: if (window.trustedTypes) { /* supported */ }. For unsupported browsers, consider using a polyfill or fallback sanitization library like DOMPurify.

Add one of these directives to your Content-Security-Policy HTTP header:

# Basic enforcement
Content-Security-Policy: require-trusted-types-for 'script';

# With a named policy
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types myPolicy;

The require-trusted-types-for 'script' directive enables enforcement. The optional trusted-types directive restricts which policy names are allowed, adding an extra layer of security.

  • TrustedHTML — For HTML content assigned to innerHTML, outerHTML, insertAdjacentHTML, etc. Created via policy.createHTML().
  • TrustedScript — For script content passed to eval(), Function(), setTimeout() with string arguments, etc. Created via policy.createScript().
  • TrustedScriptURL — For URLs passed to script loading sinks like <script src>, import(), Web Workers, etc. Created via policy.createScriptURL().

Each type corresponds to a specific injection sink category, ensuring precise control over what data reaches each dangerous API.

Yes, but it requires coordination. Many popular libraries have already adopted Trusted Types compatibility:

  • DOMPurify — Returns TrustedHTML when Trusted Types are available
  • Angular — Built-in Trusted Types support since v11
  • React — Trusted Types compatible; uses text content by default for JSX
  • Lit (LitElement) — Full Trusted Types support
  • jQuery — Version 3.5+ added Trusted Types compatibility

For libraries that don't support Trusted Types, you can create a default policy as a fallback, but this should be used sparingly as it can weaken security.

No. Trusted Types is a defense-in-depth mechanism, not a replacement for proper input validation and output encoding. It acts as a safety net at the DOM level:

  • Input validation ensures data conforms to expected formats before processing
  • Output encoding ensures data is safely rendered in the correct context (HTML, JS, CSS, URL)
  • Trusted Types ensures that even if validation/encoding fails, dangerous sinks cannot accept untrusted strings

All three layers should be used together for comprehensive XSS protection.

  • Overly permissive default policies — A default policy that passes through unsanitized strings defeats the purpose
  • Forgetting about all sinks — Remember document.write, eval, setTimeout with strings, srcdoc on iframes, etc.
  • Third-party code — Ads, analytics, and widgets may break if they use forbidden sinks
  • Dynamic code generation — Template engines that compile to string-based innerHTML need updating
  • Reporting gaps — Use report-uri or report-to alongside enforcement to catch violations without breaking users

Start with Report-Only mode to identify violations before enforcing Trusted Types in production.

New

size‑container Demo - Online Intrinsic & Styled Queries

Explore the size‑container and inline‑size CSS properties for container queries. Understand containment contexts. Visual guide.

New

EventSource Polyfill Demo - Online See SSE with Custom Headers

Demonstrate how to add custom headers and POST‑like functionality to EventSource using a polyfill. Code and example.

New

CSS resize Property Demo - Online User‑Resizable Element

Make an element resizable horizontally, vertically, or both. See the handle and code. Useful for textareas.

New

Resize Observer Playground - Online Watch Element Size

Drag to resize a box and see the Resize Observer callback fire. Get contentRect and borderBoxSize. Learn the API.

New

Furniture Anchoring Guide – Online Childproofing Selection

Select your wall type and furniture style to see the best anchoring method. Prevent tip‑over accidents.

New

Logical Sizing Properties Demo - Online block‑size & inline‑size

Compare width/height with block‑size/inline‑size in different writing modes. Understand intrinsic sizing. Copy best practices.

New

Element Resize Detector - Online Monitor Size Changes

Select any element on the test page and monitor its size changes with ResizeObserver. See log of all entries.

One Rep Max Calculator - Online Strength & Lifting Estimator

Estimate your one‑rep max (1RM) from weight and reps. Supports multiple formulas (Epley, Brzycki). Training percentages table.

New

Web HID Explorer - Online List & Read HID Devices

Request HID devices and list them. Read input reports and send output. For custom hardware and controllers.

New

scroll‑padding & scroll‑margin Demo - Online Anchor Position

See how scroll‑padding and scroll‑margin affect the position of elements when using anchor links or scroll‑snap. Visual.

New

will‑change Property Visualizer - Online GPU Hint Tool

Apply will‑change to any element and see its effect on compositing. Learn best practices for smooth animations.

New

Bird Toy Safety Checker – Online Materials & Size Guide

Select bird species and toy type to see potential hazards and size recommendations.

New

Image vs. SVG Weight Comparator - Online Byte‑for‑Byte

Paste a raster image and an SVG, see the file size and rendering time. Understand when to use vector. Local.

New

Lit Element Skeleton Generator - Online Quick Starter

Generate a Lit Element web component skeleton with styles and properties. Copy and start coding immediately.

New

Password Entropy Calculator - Online Bits of Security Meter

Calculate the entropy (in bits) of a password based on character pool size and length. Visual strength meter with crack time estimation. Local only.

New

Print CSS Generator - Online Optimize Pages for Paper

Toggle print‑specific styles like removing backgrounds, showing link URLs, and adding page breaks. Generate a complete print stylesheet instantly.

New

Reptile Hide Size Calculator – Tight Fit for Security

Calculate the appropriate hide box dimensions based on your reptile’s length and girth. A snug hide reduces stress and promotes natural behavior.

New

Font Size Scale Preview - Online Typography Visualizer

Type a few words and see them rendered at every heading size (h1–h6) with your chosen font. Perfect for design systems.

New

One Rep Max (1RM) Calculator - Online Strength Trainer Tool

Calculate your one-rep max using Epley, Brzycki, Lombardi or O'Conner formulas. Predict maximum lifting capacity and plan progressive overload. 100% local processing.

New

Photo Print Resolution Checker – Online DPI Maximum Size

Enter megapixels and desired DPI to see the maximum print size without upscaling. Quick quality check.

New

Print CSS Generator - Online Optimize Page for Paper

Add print styles like removing backgrounds, adding page breaks, setting margins. See print preview instantly.

New

Portable Generator Sizing – Online Wattage Estimator

Add appliances with running and starting watts to estimate needed generator capacity. Prevent overload.

New

One‑Rep Max (1RM) Calculator - Online Lifting Progress

Estimate your one‑rep max from weight and reps. Supports Epley, Brzycki, Lombardi formulas. See your strength level.

New

Pregnancy Weight Gain Tracker - Online Weekly Chart by BMI

Plot weekly weight gain against recommended ranges based on pre-pregnancy BMI. IOM guidelines displayed. Data stored in localStorage.

New

Rubber Band Ball Calculator – Online Estimate Bands Needed

Enter current ball size and target to find approx rubber bands required. Fun and satisfying.

New

Crochet Hat Sizing Guide – Online Measure & Increase

Enter head circumference to get crown diameter and length. Perfect fit top‑down hats.

New

Felting Shrink Calculator – Online Predict Wool Felted Size

Knit a swatch, measure before and after felting, and let this tool calculate the shrink percentage. Plan your felted projects accurately.

New

Tire Size Visualizer - Online Compare & Dimensions

Enter two tire sizes and see a side‑by‑side comparison of diameter, width, and speedometer error. Local math.

New

Body Fat Percentage Estimator - Online US Navy & Covert Bailey Method

Estimate body fat percentage using neck, waist, hip (if female) measurements. Supports US Navy, Covert Bailey, and 3-site skinfold methods. No data sent to server.

New

Shipping Box Size Optimizer - Online Fit Items into Carton

Enter item dimensions and find the smallest rectangular box that can fit them (simple packing heuristic). Helps reduce shipping costs. Local algorithm.