I am trying to make an existing php web application CSP compliant by doing away with 'unsafe-inline' in the 'script-src' directive
The code currently ( working but only due to unsafe-inline ):
// Currently - button in a php form
<button type="submit" class="btn-dark" name="button_clearUser"
onclick="return singleConfirm('Proceed ?')" >Clear Penalty</button>
// js function in an external javascript file
function singleConfirm( msg1 ) {
if (confirm(msg1)) {
return true;
} else {
return false;
}
}
To make the above fully CSP compliant, I attempted the following ...
// Amended - button in a php form - added class confirm
<button type="submit" class="btn-dark confirm" name="button_clearUser"
>Clear Penalty</button>
// Amended - added a eventListener in the external js file
// for class confirm
document.addEventListener('DOMContentReady', function () {
document.getElementsByClassName('confirm')
.addEventListener('click', return singleConfirm(msg1));
});
The above amendments are not working. And I dont see any error in the browser console. I suspect it a JS issue.
Pls advise.
................................ Updates Below ..............................
Update 3 ( the only issue left is that even when i click cancel, the form still submits. With onclick method, the 'return' keyword is used. Not sure how to implement 'return' concept here ) :::
Fixed ReferenceError: msg1 is not defined
function singleConfirm(msg1) {
if (confirm(msg1)) {
return true;
} else {
return false;
}
}
document.addEventListener('DOMContentLoaded', function () {
const elems = document.getElementsByClassName('confirm');
Array.prototype.forEach.call(elems, (elem) => {
elem.addEventListener('click', () => singleConfirm('Proceed ?'));
});
});
Update 2 :::
Used array for getElementsByClassName. With the this update, I now have a modal window popping but only if i remove msg1 ( gives ReferenceError: msg1 is not defined )
document.addEventListener('DOMContentLoaded', function () {
const elems = document.getElementsByClassName('confirm');
Array.prototype.forEach.call(elems, (elem) => {
elem.addEventListener('click', () => singleConfirm(msg1));
});
});
Update 1 :::
Replaced DOMContentReady -> DOMContentLoaded
document.addEventListener('DOMContentLoaded', function () {
});