JavaScript Document securitypolicyviolation Event

Beginner
⏱️ 13 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Document event
Baseline Widely available

What You’ll Learn

The Document securitypolicyviolation event fires when a Content Security Policy (CSP) is violated. Learn how to listen on document, read SecurityPolicyViolationEvent fields like blockedURI and violatedDirective, and practice with five try-it labs.

01

Kind

Document event

02

Type

SecurityPolicyViolationEvent

03

Bubbles

Yes (to Window)

04

Composed

Yes

05

Topic

CSP violations

06

Status

Baseline · Widely available

Introduction

A Content Security Policy tells the browser which scripts, images, styles, and other resources a page is allowed to load. When something breaks that policy—for example an image from a blocked host—the browser can fire securitypolicyviolation on the Document.

The event object is a SecurityPolicyViolationEvent. It carries details such as which URI was blocked and which CSP directive was violated, so you can log or report the problem without guessing.

💡
Beginner tip

Attach the listener on document or window (top level). MDN notes that a blocked <img> usually targets document directly—it does not reliably bubble from the image element.

Understanding Document securitypolicyviolation

A standard Document event that answers: “Did this page just break its Content Security Policy?”

  • Fires when a Content Security Policy is violated (MDN).
  • Bubbles to the Window and is composed.
  • Listen on document or window (recommended top-level targets).
  • Event typeSecurityPolicyViolationEvent (inherits from Event).
  • Handlerdocument.onsecuritypolicyviolation or addEventListener("securitypolicyviolation", ...).
  • Status — Baseline Widely available since March 2022 (MDN).

📝 Syntax

Use the event name with addEventListener, or set the handler property:

JavaScript
addEventListener("securitypolicyviolation", (event) => { });

onsecuritypolicyviolation = (event) => { };

Event type

A SecurityPolicyViolationEvent, which inherits from the generic Event type. It bubbles to Window and is composed.

MDN-style handlers

JavaScript
document.onsecuritypolicyviolation = (e) => {
  // Handle SecurityPolicyViolationEvent e here
};

document.addEventListener("securitypolicyviolation", (e) => {
  // Handle SecurityPolicyViolationEvent e here
});

Useful event properties

PropertyBeginner meaning
blockedURIURI of the resource that was blocked
violatedDirectiveWhich CSP directive was broken (alias of effectiveDirective)
originalPolicyThe policy text that caused the violation
disposition"enforce" or "report" (report-only mode)
documentURIURI of the document where it happened
sampleShort sample for some inline script/style violations
sourceFile / line / columnWhere a script-related violation occurred

⚖️ CSP event vs HTTP headers

TopicsecuritypolicyviolationCSP HTTP / meta policy
RoleJavaScript notification after a violationRules that allow or block resources
Where setdocument / window listenersContent-Security-Policy header or <meta http-equiv>
Report-onlydisposition === "report" possibleContent-Security-Policy-Report-Only
Fixes the bug?No—observes and logsYes—defines what is allowed
Beginner useDebug blocked assets in the console / UILock down scripts, images, frames, etc.

⚡ Quick Reference

GoalCode / note
Listendocument.addEventListener("securitypolicyviolation", fn)
Handler propertydocument.onsecuritypolicyviolation = fn
Log blocked URLevent.blockedURI
Which rule brokeevent.violatedDirective or event.effectiveDirective
Full policy textevent.originalPolicy
Enforce vs reportevent.disposition
MDN statusBaseline Widely available (Mar 2022)

🔍 At a Glance

Four facts to remember about Document securitypolicyviolation.

Event type
SecurityPolicyViolationEvent

CSP details included

Means
CSP broken

Resource blocked / reported

Listen on
document

Or window (top level)

Baseline
yes

Widely available

Examples Gallery

Examples follow MDN Document: securitypolicyviolation event. Try-it labs use a page CSP meta tag that blocks images from other hosts, then load a blocked <img> so you can inspect the event. Some sandboxes may limit CSP—feature-detect and fall back to a synthetic event when needed.

📚 Getting Started

Listen and log the main SecurityPolicyViolationEvent properties.

Example 1 — Log Violation Details (MDN style)

Print blockedURI, violatedDirective, and originalPolicy.

JavaScript
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.blockedURI);
  console.log(e.violatedDirective);
  console.log(e.originalPolicy);
});
Try It Yourself

How It Works

This matches MDN’s SecurityPolicyViolationEvent example: log the blocked resource, the violated directive, and the original policy string.

Example 2 — document.onsecuritypolicyviolation

Use the handler property from MDN’s Document syntax listing.

JavaScript
const out = document.getElementById("out");

document.onsecuritypolicyviolation = (e) => {
  out.textContent =
    "Blocked: " + e.blockedURI +
    " | directive: " + e.violatedDirective;
};
Try It Yourself

How It Works

Prefer addEventListener when you need more than one listener. The property form is handy for a single top-level handler.

📈 Fields, Real CSP & Synthetic

Inspect disposition, trigger a real block, or dispatch a demo event.

Example 3 — Key Fields Panel

Show disposition, documentURI, and effectiveDirective together.

JavaScript
const out = document.getElementById("out");

document.addEventListener("securitypolicyviolation", (e) => {
  out.textContent =
    "disposition: " + e.disposition + "\n" +
    "effectiveDirective: " + e.effectiveDirective + "\n" +
    "documentURI: " + e.documentURI + "\n" +
    "blockedURI: " + e.blockedURI;
});
Try It Yourself

How It Works

disposition tells you whether the UA enforced the policy or only reported it. effectiveDirective is the modern name; violatedDirective is a historical alias.

Example 4 — Trigger with a Blocked Image

Set img-src 'none' via meta CSP, then insert a remote image.

JavaScript
// Page head also needs:
// 

const out = document.getElementById("out");

document.addEventListener("securitypolicyviolation", (e) => {
  out.textContent =
    "CSP violation: " + e.violatedDirective +
    " blocked " + e.blockedURI;
});

const img = document.createElement("img");
img.alt = "blocked demo";
img.src = "https://example.com/csp-demo.png";
document.body.appendChild(img);
Try It Yourself

How It Works

The meta tag defines the policy; the image request violates img-src; the Document event reports the details. Keep script-src 'unsafe-inline' in labs so your demo script can still run.

Example 5 — Synthetic Event (Demo Fallback)

Dispatch a SecurityPolicyViolationEvent when a real CSP block is unavailable.

JavaScript
const out = document.getElementById("out");

document.addEventListener("securitypolicyviolation", (e) => {
  out.textContent =
    "Heard violation: " + e.violatedDirective +
    " → " + e.blockedURI;
});

document.getElementById("btn").addEventListener("click", () => {
  if (typeof SecurityPolicyViolationEvent !== "function") {
    out.textContent = "SecurityPolicyViolationEvent constructor missing";
    return;
  }
  document.dispatchEvent(
    new SecurityPolicyViolationEvent("securitypolicyviolation", {
      blockedURI: "https://cdn.example/demo.js",
      violatedDirective: "script-src",
      effectiveDirective: "script-src",
      originalPolicy: "script-src 'self'",
      disposition: "report",
      documentURI: location.href,
      statusCode: 200
    })
  );
});
Try It Yourself

How It Works

Useful for teaching the listener shape when the try-it iframe cannot apply a real CSP. In production, prefer real violations from your server CSP headers.

🚀 Common Use Cases

  • Logging CSP failures to your monitoring or analytics pipeline.
  • Debugging why a script, image, font, or frame was blocked.
  • Showing a gentle “resource blocked by security policy” notice in admin UIs.
  • Comparing enforce vs report-only rollouts via disposition.
  • Teaching beginners how CSP connects HTTP policy to JavaScript events.

🔧 How It Works

1

CSP is active

Policy arrives via HTTP header or <meta http-equiv="Content-Security-Policy">.

policy
2

Something breaks a rule

A script, image, style, or other resource violates a directive such as img-src.

violation
3

Document event fires

securitypolicyviolation runs on the document (and can bubble to window).

event
4

You inspect the details

Read blockedURI, directives, disposition, and related fields.

📝 Notes

  • Baseline Widely available (since March 2022)—no Deprecated / Experimental / Non-standard banner.
  • Bubbles to Window and is composed—still prefer top-level listeners.
  • Blocked elements often target document directly (MDN), not the element itself.
  • The event observes violations; fixing them means adjusting your CSP policy.
  • Related learning: selectionchange, scrollsnapchanging, JavaScript hub.

Universal Browser Support

Document securitypolicyviolation is marked Baseline Widely available on MDN (since March 2022). Logos use the shared browser-image-sprite.png sprite from this project. Pair it with real CSP headers in production.

Baseline · Widely available

Document securitypolicyviolation

Fires when a Content Security Policy is violated. Inspect SecurityPolicyViolationEvent fields such as blockedURI and violatedDirective.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium Edge
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Not a modern target for this Baseline feature
Not supported
securitypolicyviolation Excellent

Bottom line: Listen on document or window, read SecurityPolicyViolationEvent details, and tighten CSP based on real violations—not only on the event.

Conclusion

Document securitypolicyviolation connects CSP enforcement to JavaScript. When a resource breaks the policy, you get a SecurityPolicyViolationEvent with the blocked URI and the directive that failed—perfect for logging and learning.

Continue with selectionchange, scrollsnapchanging, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Listen on document or window
  • Log blockedURI and violatedDirective
  • Check disposition during report-only rollouts
  • Prefer addEventListener for multiple handlers
  • Fix policies at the CSP source, not only in JS

❌ Don’t

  • Assume the event fires on the blocked <img> itself
  • Treat the listener as a substitute for a correct CSP
  • Ignore report-only vs enforce differences
  • Ship overly open CSP just to silence the event
  • Call this Experimental—it is Baseline Widely available

Key Takeaways

Knowledge Unlocked

Five things to remember about securitypolicyviolation

CSP broke a rule — read SecurityPolicyViolationEvent for the details.

5
Core concepts
🔍 02

Rich event type

SecurityPolicyViolationEvent

API
🔒 03

Key fields

blockedURI + directive

Debug
🎯 04

Top-level listen

document or window

Pattern
05

Baseline ready

Widely available

Status

❓ Frequently Asked Questions

What is the Document securitypolicyviolation event?

It fires when a Content Security Policy (CSP) for the document is violated—for example when a blocked script, image, or style is rejected by the policy.

Is securitypolicyviolation deprecated or experimental?

No. MDN marks Document securitypolicyviolation as Baseline Widely available (since March 2022). It is not Deprecated, Experimental, or Non-standard.

Does the event bubble?

Yes. MDN states it bubbles to the Window object and is composed. Still, you should usually listen on document or window. Blocked resources typically target document directly.

What event type is it?

A SecurityPolicyViolationEvent, which inherits from Event. Useful properties include blockedURI, violatedDirective (alias of effectiveDirective), originalPolicy, disposition, and sample.

Where should I attach the listener?

On a top-level object: Document or Window. MDN notes that although HTML elements can theoretically be targets, a blocked image typically fires with document as the target—not bubbling from the <img>.

What is disposition?

It indicates whether the user agent is configured to enforce or just report the policy violation ("enforce" or "report"), such as with Content-Security-Policy-Report-Only.

Did you know?

CSP can run in report-only mode. Violations still fire securitypolicyviolation, but disposition is "report" and the browser does not necessarily block the resource the same way as enforce mode.

Next: Document selectionchange

Learn when the document text Selection or caret changes.

selectionchange →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful