简体   繁体   English

在动态加载的页面上使用 Javascript 单击所有按钮

[英]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.我正在尝试编写一个 javascript 代码,单击https://www.teamblind.com/上讨论线程中的所有按钮,这样我就可以看到所有评论,而无需单击按钮展开它们。

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();在控制台中,我只需要重复运行 bs[0].click(); until one element is left, but when I turned that into a while loop like the following直到剩下一个元素,但是当我将其变成如下所示的 while 循环时

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.当我在 Web 控制台中运行此功能时,浏览器选项卡实际上会停止工作,我不得不使用任务管理器关闭浏览器进程以停止在控制台中运行此功能。

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编辑:单击按钮会减小bs大小在此处输入图片说明

Logging the bs size记录bs大小

![在此处输入图片说明

the btn itself might not be removed after the click, it may have became invisible.点击后 btn 本身可能不会被删除,它可能变得不可见。 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.因此for...each在 while 循环内使用for...each循环或查询元素。

So first the while loop is not needed.所以首先不需要while循环。 Let's do that with if :让我们用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:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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