Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access IIFE variables from developer tools

Let me preface this by saying that I am aware it is not programmatically access inner variables of an IIFE from outside, unless they have been made accessible to the global scope.

For example:

(function() {
    var a = "Hello"; // a isn't accessible from the outer scope
)();

console.log(a); // a is undefined

But:

(function() {
    var a = "Hello";
    global.a = a;
)();

console.log(a); // Displays "Hello"

In some cases, it is possible that the IIFE will keep executing for several seconds, or during the entire duration of the page browsing, typically in the case of games written in JavaScript, where the IIFE will contain the game loop.

Therefore, all the variables and functions declared within the IIFE must exist in the browser memory, but, due to the encapsulation, they can't be displayed from the developer console.

My question is: is there any way I could still display or manipulate those, without previously modifying the code, while it is running? Since those variables are present in memory and being used? Perhaps through debugging of some sort?

My question is mostly for Firefox and Chrome (Firebug and developer tools), but if there is a general way to do it that would work too.

like image 513
pie3636 Avatar asked Aug 25 '26 15:08

pie3636


1 Answers

Put a breakpoint inside the IIFE, on a line of code that will be run in the future.

When the breakpoint is hit, the console will be in that scope.

(function() {
  document.querySelector("button").addEventListener("click", myFunction);

  var a = 1;
  
  function myFunction (ev) {
    debugger; // You could also add this breakpoint using the Dev Tools UI
    console.log("A is ", a);
  }
})();
<button>Button</button>
like image 90
Quentin Avatar answered Aug 27 '26 04:08

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!