View source for Replace inline JavaScript

((https://en.wikipedia.org/wiki/Unobtrusive_JavaScript Unobtrusive JavaScript))
((https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes How to Use HTML5 Data Attributes))

((/Dev/Guidelines/SecurityHeaders CSP)) uses '##unsafe-inline##' or ##data:## inside ##script-src##.

file:/js_enabled.png

Replace inline JavaScript

%%oncontextmenu
onmousedown
onload
onclick
onerror
onmouseover
onmouseout%%
  3. --##<script>var dbclick = "page";</script>##-- DONE
    * use data-dbclick for page and comments

https://stackoverflow.com/questions/588040/window-onload-vs-document-onload

file:/js_disabled.png

%%//'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”); %%