Is there any way to add an eventlistener that will run whenever any of the forms in the webpage gets submitted? This need to run on all the websites, for example, on www.google.com, whenever the user searches something, the eventlistener should run.
I am not using any html file. So it is not possible to use the form id.
I am a Swift developer but need to use JavaScript in this scenario. So really need some help here.
Note: There is a similar question on StackOverflow, but that is for Ajax. I am looking to use only JavaScript.
UPDATE: I need an eventlistener that will get executed whenever a user searches something on any search engine website, like google, bing, etc. The eventlistener should run when the users 1. hits enter on the search box. 2. clicks on the search button. 3. clicks on or hits enter on the autocomplete search predictions.
as of now I am able to achieve 1 and 2 using the following code:
document.body.addEventListener('keypress', function(e) {
// check if the element is an `input` element and the key is `enter`
if((e.target.nodeName === "INPUT") && e.key === 'Enter') {
console.log('Enter pressed Input');
}
});
document.body.addEventListener('click', function(e) {
if(e.target.nodeName === "INPUT") {
console.log('Clicked Input');
}
});
document.body.addEventListener('keypress', function(e) {
if(e.target.nodeName === "DIV" && e.key === 'Enter') {
console.log('Enter pressed in Autocomplete');
}
});
document.body.addEventListener('click', function(e) {
if(e.target.nodeName === "LI") {
console.log('Clicked Autocomplete');
}
});
However, I am not able to achieve target 3 yet.
I thought maybe if I was able to implement an eventlistener that would run whenever the form gets submitted, all the three targets will be achieved. I am not sure as I am new to JavaScript.
I also need to do it without using any form id as the same code needs to be compatible with multiple forms.
I hope this makes it clearer now.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…