简体   繁体   中英

Click on all similar buttons on a web page with a delay

I am working with a database app and I sometimes I have to click on tens or even hundreds of same buttons on a web page so I thought I save some time and run a script in the Inspect -> Console window of the Crome browser to do the job for me. I found a script which does the job just fine, however the database app hangs up after the first 10-20 clicks so I spoke with our developers and they advised that there should be a small delay between the clicks. They were not sure how much though so I need to experiment with it. So, by now I am trying to run the following script:

javascript:var inputs = document.getElementsByClassName('BUTTON CLASS HERE');
$(function theLoop (i) {
setTimeout(function () {
inputs[i].click();
if (--i) {          
  theLoop(i);       
}
}, 100);
})(inputs.length);

It does nothing, but gives me the following error message: gE02JAse0g9.js:60 ErrorUtils caught an error: "Cannot read property 'click' of undefined". Subsequent errors won't be logged

There seems to be some problem with calling the inputs[i].click() within the SetTimeout function, because it works just fine if I run it in a simple for loop like this:

javascript:var inputs = document.getElementsByClassName('BUTTON CLASS HERE'); 
for(var i=0; i<inputs.length;i++) { 
inputs[i].click();
}

What am I doing wrong? Thanks.

inputs[inputs.length] (on your first iteration, i === inputs.length ) will always be undefined - array-like objects are zero-indexed in Javascript, so when inputs[i].click(); is encountered, an error is thrown.

Either initialize i to inputs.length - 1 instead, or you might find it easier to use your original code and simply await a Promise that resolves after 100ms or so:

const resolveAfter100MS = () => new Promise(res => setTimeout(res, 100));
(async () => {
  var inputs = document.getElementsByClassName('_42ft _4jy0'); 
  for(var i=0; i<inputs.length;i++) { 
    inputs[i].click();
    await resolveAfter100MS();
  }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM