【问题标题】:javascript click button if inactive for 60 seconds如果 60 秒不活动,则 javascript 单击按钮
【发布时间】:2014-10-17 07:43:33
【问题描述】:

我搜索了很长时间,制作了不同的文件,但都无法正常工作。

我需要什么: 如果我在 1 分钟内没有与网页交互,请执行以下操作: - 点击按钮。 - 如果我仍然没有互动,请在 30 秒后重复点击

当我返回网页(再次交互)时,我不希望此脚本继续运行...仅当我不再交互时。

我来了:

function findButtonbyTextContent(text) {
var buttons = document.getElementsByTagName('button');
for (var i=0; i<buttons.length; i++) {
if (buttons[i].firstChild.nodeValue == text)
  return buttons[i];
}
}

function refresh(tijd){
setInterval(findButtonbyTextContent("Refresh").click(), tijd);
}

document.onmousemove = (function() {
var onmousestop = function() {
        refresh(30000);
    }, thread;

return function() {
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 60000);
};
})();

【问题讨论】:

  • 当你点击这个按钮时会发生什么?您可以触发 javascript 函数,但您是否真的在尝试触发一些原生事件等。如果是这样,那会有所不同吗?
  • 此刷新按钮会重新加载 iframe。我不使用按钮的 id 或名称的原因是 webapp 更改了这些值。我设法让它与您的其他答案一起使用。这很棒。

标签: javascript button click mouse


【解决方案1】:

我会这样做

var int, timer, btn = document.getElementById('button');

document.onmousemove = function () {
    clearTimeout(timer);
    clearInterval(int);
    timer = setTimeout(function() {
        int = setInterval(function() {
            btn.click();
        }, 30000);
    }, 60000);
}

FIDDLE

我给按钮一个 ID 并缩短了 Fiddle 中的时间,这样就不必等待几分钟才能看到结果。

作为旁注,你的代码有一些问题,例如这个

setInterval(findButtonbyTextContent("Refresh").click(), tijd);

立即调用 click 函数并返回 undefined,因此它根本不会像您认为的那样做,并且您不会在任何地方存储对间隔的引用,仅存储初始 setTimeout 和清除没有清除间隔,它仍在继续。

【讨论】:

  • 这很好用!我使用了函数 findButtonbyTextContent("Refresh").click() 而不是 btn.click
猜你喜欢
  • 2017-12-07
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多