Replace inline JavaScript

Unobtrusive JavaScript
How to Use HTML5 Data Attributes

CSP uses 'unsafe-inline' or data: inside script-src.

Replace inline JavaScript


  1. <script>var dbclick = "page";</script> DONE
    • use data-dbclick for page and comments[...]d-vs-document-onload

//'Getting' data-attributes using dataset 
var showhandler = document.getElementById('showhandler');
var dbclick = showhandler.dataset.dbclick1; // dbclick = 'page';	

Refactoring inline code

Unsigned JavaScript code placed inline

By default CSP disables any unsigned JavaScript code placed inline in the HTML source, such as this:

 <script>var foo = "314"<script>	

The inline code can be enabled by specifying its SHA256 hash in the CSP header:

 Content-Security-Policy: script-src 'sha256-gPMJwWBMWDx0Cm7ZygJKZIU2vZpiYvzUQjl5Rh37hKs='	

This particular script's hash can be calculated using the following command:

 echo -n 'var foo = "314"' | openssl sha256 -binary | openssl base64	

Some browsers (e.g. Chrome) will also display the hash of the script in JavaScript console warning when blocking an unsigned script.

The inline code can be also simply moved to a separate JavaScript file:

 <script>var foo = "314"<script>	


 <script src="app.js"></script>	

with `app.js` containing the `var foo = "314"` code.

Inline event handlers

The inline code restriction also applies to inline event handlers, so that the following construct will be blocked under CSP:

 <button id="button1" onclick="doSomething()">	

This should be replaced by `addEventListener' calls:

 document.getElementById("button1").addEventListener('click', doSomething);	

Variable assignment in inline scripts. Rather than do this:

 <script>var foo = "314";<script>	

Leverage HTML5's custom data attributes by setting the value as follows:

 <body data-foo="314”>

And access the value by doing:

 var itemID = document.body.getAttribute("data-foo”);