tampermonkey脚本检查按钮并单击它
我对使用Tampermonkey创建脚本的新手很新,即使在过去几个小时看了几个答案之后,我仍然无法弄清楚这个答案。
我正在尝试制作一个检查按钮的脚本,并且在出现大约2秒后单击它的脚本。
我正在尝试通过ID搜索它:
var caseHide = document.getElementById("accept");
var checkTimer = setInterval(MyTimer, 1500);
function MyTimer() {
if (caseHide.offsetParent === null)
{
return;
}
var eek = document.getElementById("accept");
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
eek.dispatchEvent(evt);
}
checkTimer();
但是,当按钮出现时,它没有单击。
我还必须提到,这是一个没有设定间隔的按钮,因为它是由警报提示的,因此我无法真正说出它的频率。
I am pretty new to creating scripts with tampermonkey and even after looking at several answers for the past few hours I still cant figure this one out.
I'm trying to make a script that checks for a button and when it appears for it to click it after about 2 seconds.
I am trying to search it by ID like this:
var caseHide = document.getElementById("accept");
var checkTimer = setInterval(MyTimer, 1500);
function MyTimer() {
if (caseHide.offsetParent === null)
{
return;
}
var eek = document.getElementById("accept");
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
eek.dispatchEvent(evt);
}
checkTimer();
However when the button appears it's not being clicked.
I also must mention that this is a button that appears without a set interval because it's prompted by an alert, and as such I can't really say how often it will appear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些想法。
第一个
getElementById
可能会失败,因为该按钮可能尚不存在。另外,仅搜索
#accept
可能不足以实际找到元素。这取决于您的页面的外观。这是我要做的。在DevTools控制台中,请执行此操作:
如果它返回未定义,则您的CSS选择器不够具体。您可能必须再走一棵树 ……类似:
你知道我的意思吗?从树上开始,然后走到元素。如果它在DevTools中不起作用,则在Tampermonkey中无法使用。在诸如Angular/React/Svelte/etc之类的现代库中,您可能拥有多个具有相同ID的元素...因此,指定单个元素可能找不到它。
然后,您的功能看起来像:
参考:
https://wwww.youtube.com/watch ?
sowajlx1uka
A few thoughts.
The first
getElementById
will probably fail since that button likely does not exist yet.Also, simply searching for
#accept
might not be enough to actually locate the element. It depends what your page looks like.Here's what I do. In DevTools console, do this:
If it comes back undefined, then your css selector is not specific enough. You may have to walk the tree a bit more... something like:
Do you know what I mean? Starting farther up the tree and walking down to the element. If it doesn't work in DevTools, it won't work in TamperMonkey. In modern libraries like Angular/React/Svelte/etc, you might have more than one element with the same ID... so just specifying the single element might not find it.
Then, your function can look like this:
References:
https://www.youtube.com/watch?v=Pr4LLrmDLLo
https://www.youtube.com/watch?v=SowaJlX1uKA