我一直收到这个错误:
拒绝执行内联脚本,因为它违反了以下内容安全策略指令:"default-src'self'data:gap:http ://www.visitsingapore.com https : //ssl.gstatic.com'unsafe-eval'" .可以使用'unsafe-inline'关键字,散列('sha256-V +/U3qbjHKP0SaNQhMwYNm62gfWX4QHwPJ7We1PXokI =')或nonce('nonce -...')来启用内联执行.另请注意,'script-src'未显式设置,因此'default-src'用作后备.
任何人都可以告诉我如何解决这个问题,这是什么意思?我的代码是:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:gap: http://www.visitsingapore.com https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">
<script src="lib/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="scripts/key.js"></script>
<script>$.ajax({
url: ' http://www.visitsingapore.com/api.listing.en.json',
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('email ID', '-------@gmail.com');
xhr.setRequestHeader('token ID', '-------');
},
data: {},
success: function (qwe12) {
var TrueResult2 = JSON.stringify(qwe12);
document.write(TrueResult2);
},
error: function () { },
});</script>
Run Code Online (Sandbox Code Playgroud) 我正在向一个站点添加 CSP 标头,该站点在采用严格的策略之前还有很长的路要走。有相当多的内联脚本,因此我使用 nonce- 来允许特定的内联脚本。我发现它不适用于onload带有 src 的脚本标记的属性。这是一个例子:
// header:
Content-Security-Policy: script-src self https: 'nonce-d3adbe3fed'
<script async defer src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" nonce="d3adbe3fed" onload="console.log('onload', _.VERSION)"></script>
Run Code Online (Sandbox Code Playgroud)
完整的工作演示位于https://brave-pasteur-0d438b.netlify.com/
Chrome 给出以下错误:
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src self https: 'nonce-d3adbe3fed'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
Run Code Online (Sandbox Code Playgroud)
该消息表明应该可以使用随机数启用内联事件处理程序,但据我所知,随机数仅适用于内联脚本。
这只是一个演示,但用例是一个异步/延迟跟踪脚本,它加载跟踪库,然后在onload处理程序中对加载的库进行跟踪调用。
是否可以在一个onload或其他事件处理程序属性上使用随机数,或者我需要更改我的实现吗?使用script-src 'unsafe-inline'orscript-src-attr 'unsafe-inline'不是一个选项,因为这些是我专门试图解决的漏洞。并且将处理程序的内容onload放入脚本标记后面的单独脚本中也不是一个选项,因为脚本是async deferred …