CSPViolationReportBody: toJSON() method

The toJSON() method of the CSPViolationReportBody interface is a serializer, which returns a JSON representation of the CSPViolationReportBody object.

The existence of a toJSON() method allows CSPViolationReportBody objects to be converted to a string using the JSON.stringify() method.

This is used by the reporting API when creating a serialized version of a violation report to send to a reporting endpoint.

Syntax

js
toJSON()

Parameters

None.

Return value

A JSON object that is the serialization of the CSPViolationReportBody object.

Examples

In this example we create a new ReportingObserver to observe CSP violation reports, then return a JSON representation of the first entry.

js
const observer = new ReportingObserver(
  (reports, observer) => {
    const firstReport = reports[0];
    // Log JSON object
    console.log(firstReport.toJSON());
    // Log JSON object as a string
    console.log(JSON.stringify(firstReport));
  },
  {
    types: ["csp-violation"],
    buffered: true,
  },
);

observer.observe();

We call toJSON() on the firstReport, which is a Report instance, which in turn results in the toJSON() defined in this interface being called to serialize the body of the report.

For the purpose of demonstration we also call JSON.stringify() on firstReport to create a string containing the JSON data. When sending or storing report information it is more common to do this than use toJSON() directly.

Specifications

Specification
Content Security Policy Level 3
# dom-cspviolationreportbody-tojson

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
toJSON

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support