简体   繁体   中英

How to have Tampermonkey script run once per page load?

I'm trying to make a tampermonkey script that will once run once per page load, and will only run again once the page has been refreshed. Here is my script so far:

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

The problem is, tampermonkey will continuously run the script, so dostuff() will just keep running over and over again, which I don't want. I've tried solutions such as GM_setValue and GM_getValue, but the solutions I found will only run once per install, which I don't want.

Here is a more complete sample of my code, which you can put in for https://stackoverflow.com (WARNING: This will crash your browser:):

$(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);
          };
function() {
  //checks if value exists
  if (!sessionStorage.getItem("___thing___")) {

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

    yourFunction();
  }
}

I'm an absolute idiot. The script was actually running once correctly, but my document.getElementsByClassName was calling recursively every time it opened a new tab. I just had to add an if statement to check for an element exclusively on the page before it opened and the problem was fixed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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