简体   繁体   中英

Clicking All Buttons with Javascript on a Dynamically Loaded Page

I'm trying to write a javascript code that click all the button in a discussion thread on https://www.teamblind.com/ , so I can see all the comments without clicking buttons to expand them.

I found I can click all the buttons by doing the following

var bs = document.getElementsByClassName('btn_more');
bs[0].click(); 

in the console, I just have to repeatedly run bs[0].click(); until one element is left, but when I turned that into a while loop like the following

function clickall() {
var bs = document.getElementsByClassName('btn_more');
while (bs.length > 1 ) { // 1 because the last button directs to other page, all other buttons expands the contents in the current thread
bs[0].click(); 
}
  return;
}

the browser tab would actually stops working when I run this function in the web console, I had to use task manager to shutdown a browser process to stop this function running in the console.

One of my guess is that the page loads dynamically, and maybe I need wait for the page to expands? Does anyone know why the tab can hang from running such a function and how this should be fixed?

EDIT: Clicking a button decreases the bs size在此处输入图片说明

Logging the bs size

![在此处输入图片说明

the btn itself might not be removed after the click, it may have became invisible. And aside from that, the buttons have already been collected before the loop so if they get removed, this might be the reason the error is being caused, a node that can't be found is being applied a function. So instead use a for...each loop or query elements each time inside the while loop.

So first the while loop is not needed. Let's do that with if :

function clickall() {
  var bs = document.getElementsByClassName('btn_more');

  // 1 because the last button directs to other page,
  // all other buttons expands the contents in the current thread
  if ( bs.length > 1 ) {
    bs[0].click(); 
  }
}

So we only click this button once. Now we can run that code regularly:

// You can stop the loop with window.clearInterval(intervalHandle); when you want.
let intervalHandle = window.setInterval(clickall, 500);

Further reading:

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