使用javascript检测CSP违规 [英] Detect CSP violations with javascript

查看:113
本文介绍了使用javascript检测CSP违规的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用javascript检测到违反内容安全策略的行为?

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

我的CSP工作并发送其报告,在该报告中我看到一些URL被注入,可能是通过浏览器插件。我想向用户显示一些插件试图修改页面的提示。

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.

我能以某种方式检测到使用javascript终止的连接(它本身已列入白名单)当然是CSP)?

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

推荐答案

根据 W3C CSP规范,违反将触发 securitypolicyviolation 事件。您可以为此添加事件监听器。

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.

在Firefox版本中,您需要启用 security.csp.enable_violation_events 首选项才能启用此功能。请参阅 Firefox中的实验功能文档。

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

这篇关于使用javascript检测CSP违规的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆