2

次のコードで Greasemonkey/Tampermonkey スクリプトを作成しました。

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


通常、機能はアクティブですが、いくつかのケースでは、ブラウザの JavaScript コンソールから無効にしたいと考えています。
Web ページに余分なトグル ボタンを追加したくありません。

どうすればこれを達成できますか?は「定義されon = trueていない」ため、コンソールに と入力しても機能しません。on

4

1 に答える 1

4

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.

于 2013-10-10T06:20:50.350 に答える