JavaScript Element securitypolicyviolation Event

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
DOM event
Instance event

What You’ll Learn

The securitypolicyviolation event fires when a Content Security Policy (CSP) is violated. Learn SecurityPolicyViolationEvent, why you usually listen on document / window, key properties such as blockedURI and violatedDirective, and five try-it labs.

01

Kind

Instance event

02

Type

SecurityPolicyViolationEvent

03

When

CSP is violated

04

Handler

onsecuritypolicyviolation

05

Bubbles?

Yes (composed)

06

Status

Baseline widely available

Introduction

A Content Security Policy tells the browser which scripts, images, styles, and other resources a page may load. When something breaks that policy, securitypolicyviolation fires so you can log, debug, or report it.

The event is documented on Element, but MDN notes you should generally attach the handler to a top-level object (Window or Document). In practice, a blocked resource (such as an <img>) often targets document directly rather than bubbling from the element.

💡
Beginner tip

Prefer document.addEventListener("securitypolicyviolation", ...) or window for reliable coverage. Read blockedURI and violatedDirective first—they answer “what was blocked?” and “which rule stopped it?”

Understanding securitypolicyviolation

An instance event that answers: “Did this page break its Content Security Policy?”

  • Trigger — a resource or inline content violates CSP.
  • Event typeSecurityPolicyViolationEvent.
  • Bubbles & composed — reaches Window.
  • Listen high — prefer document / window.
  • Baseline Widely available on MDN (since October 2018).

🔒 CSP in One Minute

Policies can arrive via HTTP headers or a <meta http-equiv="Content-Security-Policy"> tag. Example that blocks remote images while allowing inline scripts for demos:

JavaScript
<meta http-equiv="Content-Security-Policy"
  content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'none'">

Loading an external image under that policy triggers securitypolicyviolation so your listener can inspect the details.

📝 Syntax

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

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

onsecuritypolicyviolation = (event) => { };

Event type

A SecurityPolicyViolationEvent (inherits from Event).

Handy properties

PropertyMeaning
blockedURIURI of the resource that was blocked
violatedDirectiveDirective that was violated (alias of effectiveDirective)
effectiveDirectiveDirective that was violated
originalPolicyFull policy string that caused the violation
disposition"enforce" or "report"
documentURIURI of the document / worker where it happened
sampleShort sample for some inline script / style violations
sourceFile / lineNumber / columnNumberLocation hints when a script caused the violation

⚡ Quick Reference

GoalCode / note
Listen (recommended)document.addEventListener("securitypolicyviolation", fn)
Handler propertywindow.onsecuritypolicyviolation = fn
What was blocked?event.blockedURI
Which rule?event.violatedDirective
Full policyevent.originalPolicy
MDN statusBaseline Widely available (Oct 2018)

🔍 At a Glance

Four facts to remember about securitypolicyviolation.

Event type
SecurityPolicyViolationEvent

CSP details

Means
CSP broken

Resource blocked

Listen on
document

or window

Baseline
yes

Since Oct 2018

Examples Gallery

Examples follow MDN Element: securitypolicyviolation event and SecurityPolicyViolationEvent. Try-it labs use a tight CSP meta tag, then intentionally load a blocked image.

📚 Getting Started

MDN-style listeners on document and window.

Example 1 — Listen on document (MDN-style)

Log 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

After a CSP violation occurs, the SecurityPolicyViolationEvent carries the blocked resource and which directive stopped it.

Example 2 — window.onsecuritypolicyviolation (MDN)

Same idea using the global handler property on window.

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

window.addEventListener("securitypolicyviolation", (e) => {
  // Handle SecurityPolicyViolationEvent e here
});
Try It Yourself

How It Works

MDN shows both forms on the top-level Window. Prefer addEventListener when you need multiple handlers.

📈 Properties, Disposition & Counts

Inspect the event object and track how often violations fire.

Example 3 — Read Key Properties

Show a compact summary when a blocked image triggers CSP.

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

document.addEventListener("securitypolicyviolation", (e) => {
  out.textContent =
    "directive=" + e.violatedDirective +
    "\nblocked=" + e.blockedURI +
    "\ndisposition=" + e.disposition;
});

// Trigger: policy has img-src 'none'
const img = new Image();
img.src = "https://example.com/blocked.png";
Try It Yourself

How It Works

Register the listener first, then cause a known violation so the handler runs with a real event.

Example 4 — Check disposition

See whether the browser is enforcing or only reporting the policy.

JavaScript
document.addEventListener("securitypolicyviolation", (e) => {
  if (e.disposition === "enforce") {
    console.log("Blocked by enforced CSP:", e.blockedURI);
  } else {
    console.log("Report-only CSP violation:", e.blockedURI);
  }
});
Try It Yourself

How It Works

Report-Only policies can still fire the event with disposition: "report" without blocking the resource.

Example 5 — Count Violations

Increment a counter each time CSP blocks another resource load.

JavaScript
const out = document.getElementById("out");
let n = 0;

document.addEventListener("securitypolicyviolation", (e) => {
  n += 1;
  out.textContent =
    "violations=" + n +
    " · last=" + e.violatedDirective;
});

["a.png", "b.png", "c.png"].forEach((name) => {
  const img = new Image();
  img.src = "https://example.com/" + name;
});
Try It Yourself

How It Works

Each blocked load can produce its own violation event—useful for dashboards and debugging noisy third-party tags.

🚀 Common Use Cases

  • Log CSP breaks during staging before tightening production policy.
  • Send violation details to your monitoring / analytics pipeline.
  • Debug which third-party script or image is blocked by script-src / img-src.
  • Distinguish enforce vs report-only with disposition.
  • Surface a friendly “resource blocked by security policy” message for developers.

🔧 How It Works

1

CSP is active

Policy arrives via HTTP header or meta tag.

Setup
2

Resource violates policy

Browser blocks (or report-only flags) the load.

Trigger
3

Event fires

SecurityPolicyViolationEvent on document / window path.

Event
4

Inspect & report

Read blockedURI, directives, disposition; log or alert.

📝 Notes

  • MDN: Baseline Widely available (since October 2018) — no Deprecated / Experimental / Non-standard banner.
  • Prefer listeners on document or window, not individual elements.
  • Bubbles to Window and is composed.
  • Also available for workers via WorkerGlobalScope.
  • Related learning: scrollsnapchanging, addEventListener(), JavaScript hub.

Browser Support

securitypolicyviolation is marked Baseline Widely available on MDN (since October 2018). Logos use the shared browser-image-sprite.png sprite from this project. Listen on document or window and read SecurityPolicyViolationEvent details.

Baseline · Widely available

Element securitypolicyviolation

Fires when Content Security Policy is violated. Chrome 41+, Firefox 63+, Safari 10+, Edge 15+, Opera 28+.

Full Widely available
Google Chrome 41+
Supported
Mozilla Firefox 63+
Supported
Apple Safari 10+
Supported
Microsoft Edge 15+
Supported
Opera 28+
Supported
Internet Explorer Not supported
Unavailable
securitypolicyviolation Baseline

Bottom line: Attach to document/window, inspect blockedURI and violatedDirective, and use disposition to tell enforce from report-only.

Conclusion

securitypolicyviolation is the standard client-side signal that CSP blocked or reported something. Listen on document or window, read SecurityPolicyViolationEvent fields, and use that data to harden your policy safely.

Continue with touchcancel, addEventListener(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Listen on document or window
  • Log blockedURI and violatedDirective
  • Register the listener before triggering test loads
  • Use Report-Only CSP while tuning a new policy
  • Prefer addEventListener for multiple handlers

❌ Don’t

  • Rely on listening only on a child <img> / script element
  • Ignore disposition when mixing enforce and report-only
  • Ship a broken CSP without monitoring violations
  • Assume every property is filled for every violation type
  • Overwrite onsecuritypolicyviolation if you need multiple listeners

Key Takeaways

Knowledge Unlocked

Five things to remember about securitypolicyviolation

CSP broke something—listen high, read blockedURI and the directive.

5
Core concepts
📄02

Event

SecurityPolicyViolationEvent

API
🔍03

Listen

document / window

Target
🚩04

Fields

blockedURI + directive

Data
🎯05

Baseline

since Oct 2018

Status

❓ Frequently Asked Questions

It fires when a Content Security Policy (CSP) is violated—for example when a blocked script, image, or style is refused by the policy.
No. MDN marks Element securitypolicyviolation as Baseline Widely available (since October 2018). It is not Deprecated, Experimental, or Non-standard.
A SecurityPolicyViolationEvent, which inherits from Event. Useful properties include blockedURI, violatedDirective, effectiveDirective, originalPolicy, and disposition.
MDN recommends adding the handler on a top-level object such as Window or Document. In practice the event often targets document (for example a blocked image), rather than bubbling from the HTML element.
Yes. It bubbles to the Window object and is composed, so top-level listeners can observe violations from the page.
A string indicating whether the user agent is configured to enforce the policy or only report the violation (enforce vs report).
Did you know?

A blocked <img> usually fires securitypolicyviolation with document as the target—not the image element itself. That is why MDN steers you toward top-level listeners.

Next: touchcancel

Clean up when a touch gesture is aborted by the system.

touchcancel →

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