In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?


If it's inside a closure, i'm pretty sure you can't.

Otherwise you just do functionName(); and hit return.


An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function

//this will fail
$(document).ready(function () {
    myFunction(alert('doing something!'));
    //other stuff
})

To succeed move the function outside the document ready function

//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {          
    //other stuff
})

Then in the console window, type the function name with the '()' to execute the function

myFunction()

Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name

function myFunction(alert('doing something!'))

Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.


This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here