Discussions » Development

How do I debug a userscript by printing its variable in the console?

§
Posted: 03-04-2022

I am trying to create a [userscript][1] for Firefox (to run in [greasemonkey][2]) and this following code doesn't work for a userscript

userscript.js

var myfruit = "apples"

Firefox Console

console.log(myfruit);

I get this error

Uncaught ReferenceError: myfruit is not defined

Using Ctrl + Shift + J to open the browser console doesn't work either.

I'm using Firefox 98

§
Posted: 04-04-2022
Edited: 04-04-2022

1 Go to Sources
2 On Sources selected Tampermonkey or your script manager extension name
3 select your script
4 Select a few break points
5 Watch the "Scope" section of the console

§
Posted: 05-04-2022
Edited: 05-04-2022

myfruit is not defined

That's because the variable in a different scope and is only visible at userscript.js scope. If you want to reach a userscript.js variable from a browser console, you'll need to set it through the unsafeWindow.myfruit...

Also for that you might need to do // @grant unsafeWindow

§
Posted: 06-04-2022

I tried your solution Konf and now it works. Thank you for your help.

NWP
§
Posted: 02-03-2024

Tampermonkey on Firefox doesn't show up anymore in the Debugger > Sources, hence you can't find your userscript/s anymore.

But I came up with this solution:

  1. Go to Debugger > Search and click on the .* button
  2. In the Search bar type in one word from the title of the userscript add the symbols .* and then add "users.js" to it

For example, I have this userscript that works with openai.com:

https://greasyfork.org/en/scripts/486705-keyboard-shortcut-for-switching-between-chat-gpt-3-5-and-chat-gpt-4

To find it in the Search tab, I have to type in, for example:

between.*user.js

, as seen here:

Or, if you want to find all the loaded userscripts type this down in the Search bar:

user.js

For simplicity, just use debugger.


var myfruit = "apples"

function(){
   .....


   debugger;

   .....
}

Then your Ctrl + Shift + J window will automatically paused at the line of debugger;

For details, see

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger

Post reply

Đăng nhập để bình luận