I was wondering if someone searched "alert(1)" on my website and I want to handle this search query from being executed without putting the XSS-protection or CSP headers. (just for the test purpose)
like this = if alert -> then do something
I was wondering if someone searched "alert(1)" on my website and I want to handle this search query from being executed without putting the XSS-protection or CSP headers. (just for the test purpose)
like this = if alert -> then do something
This will NOT prevent XSS attacks! XSS attacks don't typically use alerts. To prevent XSS attacks, you need to sanitize all inputs.
If you still want to check for alerts for whatever reason:
You could check if the window lost focus, but that's about all you can do to detect alerts with vanilla JS.
function doAlert() {
alert("hi!!");
}
document.body.addEventListener('focusout', (event) => {
console.log("out");
});
<button onclick="doAlert();">alert</button>
This will only execute after the alert has been dismissed though as alerts pause JavaScript. It also detects whenever you switch tabs or open another app.