Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Run a Greasemonkey Script only once

Tags:

greasemonkey

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 only once and then like delete itself or make itself inactive?

Thanks.

like image 579
C0dez Avatar asked Mar 06 '13 14:03

C0dez


People also ask

How to run Greasemonkey script in Firefox?

Installing the Greasemonkey Extension. Click on the Firefox drop-down menu at the top left of the browser and select Add-ons. Type Greasemonkey into the add-ons search box at the top right of the browser. Find Greasemonkey in the list and click on Install.

How does Greasemonkey work?

GreaseMonkey is a Firefox extension that lets you run arbitrary Javascript code against selected web pages. What this means is that GreaseMonkey lets you change how other people's web pages look and how they function (but just in your own browser, of course).


2 Answers

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.");
}
like image 192
Brock Adams Avatar answered Oct 07 '22 01:10

Brock Adams


Redefine the function as the last statement in the body:

function foo()
 {
 ...
 foo = function(){};
 }
like image 30
Paul Sweatte Avatar answered Oct 06 '22 23:10

Paul Sweatte