最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to control a Tampermonkey script's function from the browser's JS console? - Stack Overflow

programmeradmin1浏览0评论

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".

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".

Share Improve this question edited Oct 10, 2013 at 6:25 Brock Adams 93.6k23 gold badges241 silver badges305 bronze badges asked Oct 9, 2013 at 12:36 JHnetJHnet 4716 silver badges19 bronze badges 1
  • Not sure what you want to do here, but you can add a line in your script: "debugger;". When you are in google chrome devtools(F12), then you can refresh the webpage and the script will stop at the point where you have that line. Then you can open the JS console and script "live" on the page. – patchie Commented Oct 9, 2013 at 14:07
Add a ment  | 

1 Answer 1

Reset to default 6

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 plete 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.

发布评论

评论列表(0)

  1. 暂无评论