4

现有代码

我在 ViolentMonkey(或 GreaseKit 或 TamperMonkey)中使用以下代码每 30 秒刷新一次页面:

setTimeout(function(){ location.reload(); }, 30*1000);

我可以让它停下来吗?

这多年来一直运行良好。但是现在,如果存在以下短语,我希望我的代码不刷新页面:Important shizzle

(我不希望它在这种情况下刷新的原因是因为那样我将不再能够看到写入的内容。)

我没有开悟

我几乎不知道 Javascript。我在 YouTube 上看过教程,尝试学习基础知识。我经常用谷歌搜索小问题并在 Stackoverflow 上找到答案(谢谢)——但我还是很慢


战略思路

  1. 搜索短语Important shizzle- 如果存在,则结束脚本。
  2. 然后我只需要我现有的代码:setTimeout(function(){ location.reload(); }, 30*1000);

唉,我找不到一个优雅的 Javascript 命令来突然结束脚本。

这行得通吗?

if( !document.body.textContent.includes("Important shizzle")) location.reload();

问题是上面不是每30秒做一次,它只是做一次

4

3 回答 3

3

您可以读取.innerTextbody 的属性,然后使用String#includes来查看您的短语是否存在。

如果它存在,您可以return退出该函数来结束脚本。

像这样的东西:

const timeout = setTimeout(function () {
  if (document.body.innerText.includes('Important shizzle')) return;
  location.reload();
}, 30 * 1000);
于 2021-08-28T19:36:35.440 回答
2

你可以这样做:

setInterval(reload, 30*1000);

function reload() {
    if ( isReloadOK() ) location.reload();
}

function isReloadOK(){
    if (document.body.textContent.includes("Important shizzle")) return false;
    return true;
}
于 2021-08-28T20:37:13.180 回答
1

你可以有超时,你可以添加一个间隔,我将使用你已经展示的例子..最重要的部分是clearTimeout

var timeout=setTimeout(function(){ location.reload(); }, 30*1000);
var interval=setInterval(()=>{
  let condition = document.body.textContent.includes("Important shizzle");
  if(condition){clearTimeout(timeout); clearInterval(interval)}
},0);
于 2021-08-28T20:43:15.933 回答