TrustedScriptURL: 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 TrustedScriptURL interface returns a string representing the TrustedScriptURL object. This is the same string that TrustedScriptURL.toString() returns.
The method is automatically called by JSON.stringify() when a TrustedScriptURL object is encountered during JSON serialization. The serialized value can then be converted back using the TrustedTypePolicy.createScriptURL() 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 TrustedScriptURL object. Calling toJSON() directly returns its stored string value.
const sanitized = scriptPolicy.createScriptURL(
"https://example.com/my-script.js",
);
const json = sanitized.toJSON();
console.log(json); // Same value as sanitized.toString()
console.log(typeof json); // "string"
Serializing to a JSON string
The TrustedScriptURL 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:
"https://example.com/my-script.js"
Specifications
| Specification |
|---|
| Trusted Types> # dom-trustedscripturl-tojson> |