I am currently working on some frontend development on a server. However when I try to add inline css and javascript for my password visibility toggle I keep getting the same CSP errors in google chrome.
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' ssl.google-analytics.com
The code I have tried :
<input id="password" type="password" name="password" class="block full-width mb2 field-light input-shadow"> <span toggle="#password" class="hidden toggle-password icon-eye" id="togglePassword"></span> <style $nonceAttr> .toggle-password { width: 20px; height: 20px; position: absolute; margin-top: -47px; right: 3.2rem; cursor:pointer; background-position: center; } .icon-eye { background-image: url(/images/eye-icon.svg); background-repeat: no-repeat; } .icon-eye-slash { background-image: url(/images/eye-slash-icon.svg); background-repeat: no-repeat; } form input::-ms-reveal, form input::-ms-clear { display: none; } input[type=password].password-form-field, input[type=text].password-form-field { padding-right: 46px !important; } </style> <script type="application/javascript" $nonceAttr> $("form input[type='password']").on("input", function(){ if($(this).val()) { $(this).next(".toggle-password").removeClass("hidden"); } else { $(this).next(".toggle-password").addClass("hidden"); } }); $(".toggle-password").click(function() { $(this).toggleClass("icon-eye icon-eye-slash"); var input = $($(this).attr("toggle")); if (input.attr("type") == "password") { input.attr("type", "text"); } else { input.attr("type", "password"); } }); </script>
It works great on both internet explorer and microsoft edge, but refuses to work on google chrome. I would need help figuring out this problem. Is it that CSP has no support for $(“.toggle-password”).click? I also tried move the js and css into seperate external files but without success.
Advertisement
Answer
Try adding ‘unsafe-inline’ to your CSP list.
E.g.,
script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval’ ssl.google-analytics.com