您可以使用事件"securitypolicyviolation"
尝试捕获CSP违规错误。
来自:https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent
示例:
document.addEventListener("securitypolicyviolation", (e) => {
console.log(e.blockedURI);
console.log(e.violatedDirective);
console.log(e.originalPolicy);
});
从https://github.com/angular/angular.js/blob/cf16b241e1c61c22a820ed8211bc2332ede88e62/src/Angular.js#L1150-L1158,函数noUnsafeEval
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
如果连接速度较慢,超时时间可能需要延长。我使用Onload来检测它,似乎可以工作。如果加载成功,则CSP显然未启用或配置不正确。
var CSP = 0;
frame = document.createElement('script');
frame.setAttribute('id', 'theiframe');
frame.setAttribute('src', location.protocol+'//example.com/');
frame.setAttribute('onload', 'CSP=1;');
document.body.appendChild(frame);
setTimeout(function(){if (0 == CSP){alert("CSP IS ENABLED");}}, 250);
黑客可以通过注入恶意代码,从你的网站中窃取用户的信用卡号和密码。这种攻击方式被称为“形式填写攻击”,因为它利用了网站上的表单填写功能。
fetch(document.location.href)
.then(resp => {
const csp = resp.headers.get('Content-Security-Policy');
// does this exist? Is is any good?
});
但是如果connect-src='none'
,则此操作将失败并报告错误。
检测CSP支持的简单方法是通过检查是否可以运行JavaScript的eval()方法而不会抛出错误,如下所示:
try {
eval("return false;");
} catch (e) {
return true;
}
目前,在运行中的浏览器中没有办法实现这一点。
然而,根据规范,以下内容应该可以工作,并且在启用实验性网络平台功能的Chrome浏览器中可以正常工作:chrome://flags/
。
function detectCSPInUse() {
return "securityPolicy" in document ? document.securityPolicy.isActive : false;
}
如果document.securityPolicy
被实现,你可以从中得到 SecurityPolicy
接口。该接口有一些属性,可以提供更详细的信息以确定当前允许什么。
chrome://flags/
,打开它并重新启动浏览器。但是,如果API可用,您现在可以实现它--上面的代码旨在工作。 - AndrewFSecurityPolicy
接口了。 - gsnedders我正在检查我的书签代码中的onError事件,并在脚本未加载时提示用户安装我的扩展程序。
javascript:(function(){
var s=document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','https://example.ru/bookmarklet?hostname=%27+encodeURIComponent(location.hostname));
s.setAttribute('onerror', 'if(confirm(`Downloading from the site is possible only through the "MyExtensionName" extension. Install extension?`)){window.open("https://chrome.google.com/webstore/detail/myextensionlink");}');
document.body.appendChild(s);})();
<script>var test=true;</script>
注入文档中,然后检查变量是否被设置。如果CSP被执行(并且您的脚本不被允许),则此代码块将根本不会被执行。 - kravietzscript
的 onerror 事件,看看能否解决这个问题。 - onassar