0

Say I'm writing a greasemonkey/chrome extension script that needs access to a variable that's inside of a closured anonymous method, like so

$(document).ready(function() {
    var goldenTreasure = "Tasty Loins";
}

is there anyway I can get to that goldenTreasure and have me some tasty loins?

note: I can't edit the above method, it's on a site, and my extension needs access to the treasure inside.

Community
  • 1
  • 1
vvMINOvv
  • 1,768
  • 4
  • 22
  • 45

3 Answers3

1

There is no way to access a var that's inside a closure as it is a private variable that is technically hidden inside the containing closure. Only functions inside that closure may have access to it.

vvMINOvv
  • 1,768
  • 4
  • 22
  • 45
Xenyal
  • 2,136
  • 2
  • 24
  • 51
  • thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script – vvMINOvv Nov 28 '14 at 16:13
  • 1
    @vvMINOvv There is no way to access those loins for you unfortunately :P – Xenyal Nov 28 '14 at 17:24
0

Define the variable outside, then assign value inside.

var goldenTreasure;

$(document).ready(function() {
    goldenTreasure = "Tasty Loins";
}

Or another way of doing it is to assign it as a property of the window object

$(document).ready(function() {
    window.goldenTreasure = "Tasty Loins";
}
  • thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script – vvMINOvv Nov 28 '14 at 16:15
0

You can declare a variable outside of the anonymous function and just assign the one inside as its value. (do it this way if you plan to reuse goldenTreasure for another purpose inside the anonymous function.

var some;

$(document).ready(function() {
    var goldenTreasure = "Tasty Loins";
    some = goldenTreasure;
}
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
  • thank's for your help, check the clarification in my question now. the code is pre-existing on a site, and I'm just trying to get to the treasure inside with my injected script – vvMINOvv Nov 28 '14 at 16:14