TrustedScript: toJSON() method
Baseline 2026>
Newly available
Since February 2026, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Note: This feature is available in Web Workers.
The toJSON() method of the TrustedScript interface returns a string representing the TrustedScript object. This is the same string that TrustedScript.toString() returns.
The method is automatically called by JSON.stringify() when a TrustedScript object is encountered during JSON serialization. The serialized value can then be converted back using the TrustedTypePolicy.createScript() method within the reviver of JSON.parse(), which runs the policy's transformation on it again.
Syntax
toJSON()
Parameters
None.
Return value
A string.
Examples
>Calling toJSON() directly
This example creates a TrustedScript object. Calling toJSON() directly returns its stored string value.
const sanitized = scriptPolicy.createScript("eval('2 + 2')");
const json = sanitized.toJSON();
console.log(json); // Same value as sanitized.toString()
console.log(typeof json); // "string"
Serializing to a JSON string
The TrustedScript object from the previous example is serialized using JSON.stringify(), which calls the toJSON() method automatically.
console.log(JSON.stringify(sanitized));
This would log the following JSON string, including the surrounding double quotes, which are part of the string's content:
"eval('2 + 2')"
Specifications
| Specification |
|---|
| Trusted Types> # dom-trustedscript-tojson> |