1

I wrote some code in chrome console to get all the functions on a webpage:

for(var b in window) { 
   if(typeof(b) == "function") console.log(b);}

however although there are functions on the webpage the only output i get is "undefined"

4
  • try using the '===' operator Commented Sep 3, 2019 at 11:15
  • @VincentChinner Makes no difference Commented Sep 3, 2019 at 11:16
  • This will give you only window methods, not “all the functions on a webpage” Commented Sep 3, 2019 at 11:17
  • b will loop on property not value. Use typeof(window[b]) instead. Commented Sep 3, 2019 at 11:22

5 Answers 5

4

b is the KEY of the window object, window[b] is the value. The key will always be a string.

for(var b in window) { 
   if(typeof(window[b]) == "function") console.log(b);}
Sign up to request clarification or add additional context in comments.

Comments

1
for(var b in window) { 

Here, you're iterating through keys, not properties of the object. typeof of those keys is string, hence the condition under the if will never be fulfilled. And the undefined you get printed in the console is the value of the for statement (which is undefined).

Do instead

for(var b in window) { 
   if(typeof(window[b]) == "function") console.log(window[b]);}

Comments

0

b is the propery name (string), not the function itself. Try like this:

for(var b in window){
    if(typeof window[b]=='function') console.log(b)
}

Comments

0

The b variable ever is the type string, change left side condition to obtain function of window.

typeof(b)         // return string
typeof(window[b]) // return function

So the answer is this:

for(var b in window) { 
    if(typeof(window[b]) === "function") 
    {
        console.log(b);
    }
}

Comments

0

If we consider your code, 'typeof(b) == "function" ' it will never check this condition because typeof(b) is always a string.

The basic syntax to get a "string" key is obj["stringFormatKey"]. So here is the solution.

for(var b in window) { 
if(typeof(window[b]) == "function") console.log(b);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.