I wrote an Greasemonkey/Tampermonkey script with this code:

var on = true;
function doSomething(){
   if(on){
      //do stuff
   }
}
setInterval(doSomething,1000);


Normally the function is active but for some few cases, I want to disable it from the javascript console in the browser.
I do not want to add an extra toggle button to the webpage.

How can I achieve this? Entering on = true, in the console, does not work because on is "not defined".

有帮助吗?

解决方案

Greasemonkey, and Tampermonkey, operate in separate scopes from the target page, and may use a sandbox as well.

The target page and JS console can not see variables and functions defined in the script scope, but your script can inject stuff into the target page's scope.

So, place your on variable in the target page scope, and you can then control that function from the console. In this case, use unsafeWindowDoc to do that.

A complete Greasemonkey and Tampermonkey script that does that is:

// ==UserScript==
// @name     _Allow console control of Tampermonkey function
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    unsafeWindow
// ==/UserScript==

unsafeWindow.on = true;

function doSomething () {
    if (unsafeWindow.on){
        //do stuff
    }
}
setInterval (doSomething, 1000);

From the console, omit the unsafeWindow. That is, you would use:

on = false;
// OR
on = true;

to stop and start that script's action.


Note that, in Chrome, the script must be running in Tampermonkey, not Chrome's native userscript emulation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top