References

Beginner-friendly references for web development, with live, editable examples.

The HTML onsecuritypolicyviolation event

Event All modern browsers Updated
Quick answer

The HTML onsecuritypolicyviolation attribute runs JavaScript when a Content-Security-Policy directive is violated. It is an inline handler for the securitypolicyviolation event; in modern code prefer addEventListener('securitypolicyviolation', …).

Overview

The onsecuritypolicyviolation event attribute runs JavaScript when a CSP violation occurs. In JavaScript the event itself is named securitypolicyviolation. Drop the on prefix when you call addEventListener.

It is fired on the element that caused the violation and bubbles up the tree, so it is normally handled on document.

You can wire this up with the inline onsecuritypolicyviolation HTML attribute, but the modern, recommended approach is document.addEventListener('securitypolicyviolation', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<body onsecuritypolicyviolation="handler()"></body>

document.addEventListener('securitypolicyviolation', handler);

Best practices

  • Prefer document.addEventListener('securitypolicyviolation', handler) over the inline onsecuritypolicyviolation attribute; it separates behavior from markup and allows multiple handlers.
  • Attach these on window with addEventListener rather than as <body> attributes.
  • Keep these handlers fast; they run at moments that affect the whole page.
  • Remove listeners you no longer need to avoid leaks in long-lived pages.

Frequently asked questions

What is the onsecuritypolicyviolation event?
It runs JavaScript when a CSP violation occurs. In JavaScript the event is named securitypolicyviolation.
Where do I attach this event?
On document, which receives the event as it bubbles from the element that caused the violation.
Can I use it as a body attribute?
You can, but it is not forwarded to window like the page-lifecycle handlers. The event bubbles from the element that caused the violation, so a handler on <body> (or on document) sees violations from anywhere inside it.
Should I use the onsecuritypolicyviolation attribute or addEventListener?
Prefer document.addEventListener('securitypolicyviolation', …) in JavaScript. The inline onsecuritypolicyviolation attribute works but mixes behavior into the markup and allows only one handler per element.