dom / latest / globaleventhandlers / onsecuritypolicyviolation.html /

GlobalEventHandlers.onsecuritypolicyviolation

The onsecuritypolicyviolation property of the GlobalEventHandlers mixin is an event handler for processing securitypolicyviolation events.

The securitypolicyviolation event fires when there is a Content Security Policy violation.

Note: In practice you must use the implementation of this property in a top level object (i.e. Window or Document). While the property exists in HTML elements, you can't assign a handler to the property until the elements have been loaded, by which time this event will already have fired.

Syntax

onsecuritypolicyviolation = functionRef

Value

functionRef

A function name, or a function expression. The function receives a SecurityPolicyViolationEvent object as its sole argument.

Only one onsecuritypolicyviolation handler can be assigned to an object at a time.

For greater flexibility, you can pass a securitypolicyviolation event to the EventTarget.addEventListener() method instead.

Example

This code shows a very simpler top-level handler set on Window that logs a value in the event to a text area (the same approach will work with a Document). Note that in this case the Content-Security-Policy value, which is set using a meta tag, allows the 'unsafe-inline' script to run, but the image cannot be loaded.

<!DOCTYPE html>
  <html lang="en">
   <head>
     <title>Examples CSP error on page load</title>
     <meta charset="UTF-8">
     <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline';">
     </head>
   <script>
     //Assign function to onsecuritypolicyviolation global handler
     window.onsecuritypolicyviolation = function(e) {
       const log_area = document.getElementById("log");
       log_area.textContent+=e.blockedURI+"\n";
     };
   </script>
   <body>
    <h1>Image loading should fail</h1>
    <label for="log">Blocked URI</label>
    <textarea id="log" rows="2" cols="50"></textarea>
    <img src="HTTPRevved_fix_typo.png">
   </body>
  </html>

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
onsecuritypolicyviolation
97
97
93
No
83
preview
97
97
93
No
No
No

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsecuritypolicyviolation