CSPInlineJSEvaluater
Enable inline JS using validated script elements inspite of CSP
HTML
<!DOCTYPE html>
<html lang="en" nonce="EWpwjc6lt4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="application/vnd.hotelsnl.javascript" nonce="EWpwjc6lt4">
alert('should execute');
</script>
<script type="application/vnd.hotelsnl.javascript" nonce="qVsV0ayqBj">
alert('should not execute');
</script>
</body>
</html>
JavaScript
(function(window, document, undefined) {
'use strict';
/**
* The InlineScript class represents a script element containing executable JavaScript code.
*
* @param {Element} node The script element.
* @constructor
*/
function InlineScript(node) {
/**
* The script element to evaluate.
*
* @type {Element}
* @private
*/
var element = node;
/**
* Returns the underlying script element.
*
* @return {Element} The script element.
* @public
*/
this.getElement = function() {
return element;
}
}
/**
* Evaluate the JavaScript code contained within this script element.
*
* @public
*/
InlineScript.prototype.evaluate = function() {
eval(this.getElement().innerText);
};
/**
* Returns the nonce attribute set for this script element.
*
* @return {String} The nonce for this script, or empty string on failure.
* @public
*/
InlineScript.prototype.nonce = function() {
var element = this.getElement();
return (element.hasAttribute('nonce')) ? element.getAttribute('nonce') : '';
};
/**
* Tests whether the given nonce is equal to the nonce attribute of this script element.
*
* @param {String} nonce The nonce to match.
* @returns {Boolean} True if both nonce values are considered equal, otherwise false.
* @public
*/
InlineScript.prototype.matches = function(nonce) {
return (nonce === this.nonce());
};
/**
* The ScriptManager is responsible for finding and validating executable script elements.
*
* @param {String} nonce The nonce to match.
* @constructor
*/
function ScriptManager(nonce) {
/**
* The nonce to match.
*
* @type {String}
* @private
*/
var value = nonce;
...