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

No specification found

No specification data found for api.CSPViolationReportBody.toJSON.
Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility

BCD tables only load in the browser