我正在尝试开发一个渐进式 Web 应用程序,其中包括外部 JavaScript、外部 CSS、JQuery 库以及 list 和服务 worker 。
我设置了内容安全策略来加载这些内容,并在本地主机和 Google Chrome 上运行它。
这是我的 HTML 头:
<head>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://*; manifest-src 'self'">
<script src="example.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- <script src="jquery.min.js"></script> -->
<link rel="stylesheet" type="text/css" href="example.css">
<link rel="manifest" href="manifest.json">
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function(registration) {
console.log('Service worker successfully installed. Scope:', registration.scope);
}).catch(function(error) {
console.log('Service worker installation failed:', error);
});
}
</script>
<link rel="icon" href="../images/favicon.ico" type="image/x-icon" />
<title>xxx</title>
</head>
我希望一切都能正常运行,但我却收到了这些与我的声明相悖的错误:
Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('xxx'), or a nonce ('nonce-...') is required to enable inline execution.
Refused to load manifest from 'http://localhost:7681/manifest.json' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'manifest-src' was not explicitly set, so 'default-src' is used as a fallback.
即使我包含了“unsafe-inline”关键字,启用了从 https 加载脚本并且我没有声明“default-src 'none'”,所以我想我遗漏了一些东西。是什么阻止了我的脚本加载?
编辑
我明白出了什么问题:服务器在 libwebsockets 上运行,默认情况下它使用非常严格的内容安全策略。更改 lws 选项,CSP 指令从 HTML 头部正确加载。
最佳答案
CSP 指令的来源已指定 here .
引自以上来源:
The site's address may include an optional leading wildcard (the asterisk character, '*')
但是,这仍然需要一个有效的站点地址。因此 https://*
不是有效的 CSP 源,因此被忽略。
允许从所有 https 站点加载脚本:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https:; manifest-src 'self'">
关于javascript - 加载脚本和 list 违反了内容安全策略指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741444/