We recently introduced the nonce content security policy in our software. The problem is that we have hundreds of HTML elements which execute inline Javascript with onclick events and we don't want to accept 'unsafe-inline' anymore.
Is there any way of getting all the elements from a page with onclick attribute set, read the code that they execute it and add something like
$(element).click(function(){
doAction();
});
The onclick attribute is executed before any other click event handler in your JS.
function doSomething() {
console.log('I do something')
}
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
if (typeof allElements[i].onclick === 'function') {
allElements[i].addEventListener("click", function(e) {
console.log('Before I do something');
});
}
}
<div onclick="doSomething()">Click me to doSomething</div>
A trick workaround would be doing something like this :
function doSomething() {
console.log('I do something')
}
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++) {
if (typeof allElements[i].onclick === 'function') {
allElements[i].addEventListener("mousedown", function(e) {
console.log('Before I do something');
});
}
}
<div onclick="doSomething()">Click me to doSomething</div>