WackoWiki: Replace inline JavaScript

https://wackowiki.org/doc     Version: 12 (29.01.2019 19:41)

Replace inline JavaScript

Unobtrusive JavaScript[link1]
How to Use HTML5 Data Attributes[link2]

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



Replace inline JavaScript

oncontextmenu
onmousedown
onload
onclick
onerror
onmouseover
onmouseout	

  1. <script>var dbclick = "page";</script> DONE
    • use data-dbclick for page and comments

https://stackoverflow.com/ques[...]d-vs-document-onload[link4]



//'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>	


becomes:

 <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”>
   ...
</body>	


And access the value by doing:

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