How to Run a Greasemonkey Script only once

僤鯓⒐⒋嵵緔 提交于 2019-11-29 02:30:10
Brock Adams

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.");
}

Redefine the function as the last statement in the body:

function foo()
 {
 ...
 foo = function(){};
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!