Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Greasemonkey/Tampermonkey variables from the browser console?

This is example of code from the userscript:

var ExampleObj = {
  somevar1:'value1',
  somevar2:'value2',
  somevar3:'value3',
  somefunction1:function(){
    //do sth
  },
  somefunction2:function(){
    //do sth else
  }
}

And when I try to call my functions from script: everything is OK, but I can't get access from browser console:

(ReferenceError: ExampleObj is not defined)


My Greasemonkey/Tampermonkey settings (Metadata):

// ==UserScript==
// @name     [this is my secret]
// @version  1
// @run-at document-end
// @include [this is my secret]
// @grant    none
// ==/UserScript==

The script works; I just need access to those functions from the browser console.

like image 352
Łukasz Rząsa Avatar asked Apr 03 '18 15:04

Łukasz Rząsa


1 Answers

In @grant none mode, scripts still operate in a protected-ish scope. Place your object in the global scope by changing:

var ExampleObj = {

To:

window.ExampleObj = {

Then you'll be able to see and use that object. (Note that the target web page can also see and use it.)

See "Accessing Variables from Greasemonkey to Page & vice versa" for more information and for scenarios when @grant is not none.

like image 157
Brock Adams Avatar answered Sep 23 '22 15:09

Brock Adams