List all js global variables used by site (not all defined!)

前端 未结 9 1880
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 13:16

What is the way to list all global variables that have been used by the site? Can any browser javascript debugger do that? By used I mean READ, not changed/added. Detect ifr

9条回答
  •  萌比男神i
    2020-12-04 13:46

    Easy way to list your globals I use sometimes. First put this code as early as possible, before any of your scripts executed.

    var WINDOW_PROPS = Object.keys(window);
    

    Then at the moment when you need to discover your globals just do something like this:

    var GLOBALS = Object.keys(window)
        // filter the props which your code did not declare
        .filter(prop => WINDOW_PROPS.indexOf(prop) < 0)
        // prettify output a bit :) It's up to you...
        .map(prop => `${typeof window[prop]} ${prop} ${window[prop]}`)
        // sort by types and names to find easier what you need
        .sort();
    
    console.log(GLOBALS.join("\n"));
    

    I've used some ES6 features here to shorten the code. It's still not good for production, but good enough for debug purposes and should work in modern browsers.

提交回复
热议问题