How to Run a Greasemonkey Script only once

前端 未结 2 1494
陌清茗
陌清茗 2020-12-16 06:39

I made a greasemonkey script for a domain, Now how do I make it run only once? Like it starts every time the domain is accessed, I don\'t want that. How do I make it run onl

相关标签:
2条回答
  • 2020-12-16 07:09

    If you want a script (or part of a script) to run only once, then you need to store a flag in non-volatile storage. A script cannot delete itself or turn itself off. But it can exit right away rather than run any other code.

    To store things on a site-by-site (domain) basis, use localStorage. To store things on a script+namespace basis, use GM_setValue. Here's a basic script:

    // ==UserScript==
    // @name        _Run a GM script one-time only
    // @namespace   _pc
    // @include     http://YOUR_SERVER.COM/YOUR_PATH/*
    // @grant       GM_getValue
    // @grant       GM_setValue
    // ==/UserScript==
    
    var alreadyRun = GM_getValue ("alreadyRun",  false);
    
    if ( ! alreadyRun) {
        GM_setValue ("alreadyRun", true);
        alert ("This part of the script will run exactly once per install.");
    }
    
    0 讨论(0)
  • 2020-12-16 07:10

    Redefine the function as the last statement in the body:

    function foo()
     {
     ...
     foo = function(){};
     }
    
    0 讨论(0)
提交回复
热议问题