如何使Tampermonkey脚本在每个页面加载时运行一次?

时间:2020-07-07 00:25:45

标签: javascript tampermonkey

我正在尝试创建一个tampermonkey脚本,该脚本在每次页面加载时运行一次,并且仅在刷新页面后才运行。到目前为止,这是我的脚本:

function(){
 dostuff()
setInterval(location.reload.bind(location), 1000*60*60*24);
}

问题是,tampermonkey将连续运行脚本,因此dostuff()只会一遍又一遍地运行,这是我不希望的。我已经尝试过诸如GM_setValue和GM_getValue之类的解决方案,但是我发现的解决方案每次安装只能运行一次,这是我不希望的。

这是我的代码的更完整示例,您可以将其放入https://stackoverflow.com中(警告:这会使您的浏览器崩溃!):

$(document).ready(function() {
    'use strict';
      if (!sessionStorage.getItem("session")) {
          sessionStorage.setItem("session", "storage");
          myFunction();
      }
})();

function myFunction(){
     if (sessionStorage.getItem("session"));
          const galleryList = document.getElementsByClassName('question-hyperlink');
          for(var y=0; y<galleryList.length;y++){
          GM_openInTab(galleryList[y].href);
          console.log(galleryList[y].href);
          }
setTimeout(location.reload.bind(location), 1000*60*60*24);
          };

2 个答案:

答案 0 :(得分:0)

function() {
  //checks if value exists
  if (!sessionStorage.getItem("___thing___")) {

    //if it does not then set it and run the function
    sessionStorage.setItem("___thing___", "");

    yourFunction();
  }
}

答案 1 :(得分:0)

我是个白痴。该脚本实际上实际上已经正确运行一次,但是每次打开新标签时,我的document.getElementsByClassName都会递归调用。我只需要添加一个if语句即可在打开页面之前先检查页面上是否有某个元素,问题已解决。