[英]Content-Security-Policy and JavaScript
我在設置 Content-Security-Policy 時遇到問題
我有.html文件,external.css和external.js
<link rel="stylesheet" href="./style.css" type="text/css" media="screen">
<script src="./script.js"></script>
如果沒有 Content-Security-Policy 頁面的工作...
如果我設置:
Header 設置 Content-Security-Policy "default-src 'none'; child-src 'self'; connect-src 'self'; script-src 'self'; base-uri 'self'; style-src 'self';阻止所有混合內容;升級不安全請求;框架祖先“無”;object-src 'self';img-src 'self';media-src 'self';frame-src 'self';字體-src 'self'; form-action 'self';"
JavaScript 有問題。 這沒用。
如果我將.js 粘貼到 .html 文件(內部腳本)中,在 CPS 中我會重寫 script-src 'unsafe-inline' - 我的頁面可以工作......(因為沒有 CPS 設置)。 但是不安全...
如何在 CPS 中安全地設置外部 working.js? 這對我來說是一個恐怖。 非常感謝。
頁面與此相同: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox
圖片上的點擊處理程序是內聯 JS。
onclick="currentSlide(1)"
您需要將它們移動到外部 JS 文件中的處理程序。
此外,您的 CSS 也有同樣的問題,內聯 styles 將被阻止
style="width:100%"
在下面的示例中,我已將您的點擊處理程序移至外部 JS 文件,並將您的內聯 CSS 移至外部文件。
如果您在服務器上運行以下示例,您會發現第一個圖像更小並且不響應點擊事件(因為內聯 JS 和 CSS 被阻止)並且其他兩個圖像大小相同(通過外部文件中的 class 正確設置寬度)並且都響應點擊事件(因為您的 JS 不再是內聯的)。
var clickHandler = function(e){ console.log(e.target.src); } var images = document.querySelectorAll(".demo"); for (var i = 0; i < images.length; i++) { images[i].addEventListener('click', clickHandler, false); }
.container{ width: 25%; }.cursor { cursor: pointer; }.demo{ width: 100%; }
<div class="container"> <,--original image has inline JavaScript with "onclick" and inline CSS with "style=": netiehr of these will work with your CSP--> <img class="demo cursor" src="https.//placehold:it/100x100" style="width:100%" onclick="currentSlide(1)" alt="Nature and sunrise"> <.--moved the click handler into the external file using "addEventListener" and moved the inline CSS to the external CSS file - this will work with your CSP--> <img class="demo cursor" src="https://placehold.it/200x200" alt="Nature and sunrise"> <img class="demo cursor" src="https://placehold.it/300x300" alt="Nature and sunrise"> </div>
這是一個更好的例子...... http://kod.djpw.cz/dmxc
如果沒有 Content-Security-Policy,這可以工作......
我想要這個:
Header 設置 Content-Security-Policy "default-src 'none'; child-src 'self'; connect-src 'self'; script-src 'self'; base-uri 'self'; style-src 'self';阻止所有混合內容;升級不安全請求;框架祖先“無”;object-src 'self';img-src 'self';media-src 'self';frame-src 'self';字體-src 'self'; form-action 'self';"
我知道要刪除圖像中的style="width:100%"
...
我想讓onclick="openModal();currentSlide(2)"
打開第二張圖像(或onclick="currentSlide(2)"
)並關閉onclick="closeModal()"
這是我不想做的...
(例如單擊“Uložit a získat odkaz”),您將擁有自己的更新鏈接)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.