Detect CSP violations with javascript

半城伤御伤魂 提交于 2020-01-22 12:27:46

问题


Is it possible to detect a Content Security Policy violation with javascript?

My CSP works and sends its reports, where I see that some urls are injected, probably by browser addons. I would like to display a hint to the user, that some addon tries to modify the page.

Can I somehow detect the aborted connection with javascript (which is itself whitelisted in the CSP of course)?


回答1:


According to the W3C CSP specification, a violation triggers a securitypolicyviolation event. You can add an event listener for this.

document.addEventListener("securitypolicyviolation", function(e) {
    alert("Something is trying something bad!");
});

See the above link for the properties of this event.

In Firefox Release, you need to enable the security.csp.enable_violation_events preference to enable this feature. See Experimental Features in Firefox documentation.



来源:https://stackoverflow.com/questions/40053592/detect-csp-violations-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!