Find JavaScript function definition in Chrome
Chrome's Developer Tools rock, but one thing they don't seem to have (that I could find) is a way to find a JavaScript function's definition. This would be super handy for me because I'm working on a site that includes many external JS files. Sure grep solves this but in the browser would be much better. I mean, the browser has to know this, so why not expose it? What I expected was something like:
- Select 'Inspect Element' from page, which highlights the line in the Elements tab
- Right-click the line and select 'Go to function definition'
- Correct script is loaded in the Scripts tab and it jumps to the function definition
First off, does this functionality exist and I'm just missing it?
And if it doesn't, I'm guessing this would come from WebKit, but couldn't find anything for Developer Tool feature requests or WebKit's Bugzilla.
Solution 1:
Lets say we're looking for function named foo
:
- (open Chrome dev-tools),
- Windows: ctrl + shift + F, or macOS: cmd + optn + F. This opens a window for searching across all scripts.
- check "Regular expression" checkbox,
- search for
foo\s*=\s*function
(searches forfoo = function
with any number of spaces between those three tokens), - press on a returned result.
Another variant for function definition is function\s*foo\s*\(
for function foo(
with any number of spaces between those three tokens.
Solution 2:
This landed in Chrome on 2012-08-26 Not sure about the exact version, I noticed it in Chrome 24.
A screenshot is worth a million words:
I am inspecting an object with methods in the Console. Clicking on the "Show function definition" takes me to the place in the source code where the function is defined. Or I can just hover over the function () {
word to see function body in a tooltip. You can easily inspect the whole prototype chain like this! CDT definitely rock!!!
Hope you all find it helpful!
Solution 3:
You can print the function by evaluating the name of it in the console, like so
> unknownFunc
function unknownFunc(unknown) {
alert('unknown seems to be ' + unknown);
}
this won't work for built-in functions, they will only display [native code]
instead of the source code.
EDIT: this implies that the function has been defined within the current scope.
Solution 4:
2016 Update: in Chrome Version 51.0.2704.103
There is a Go to member
shortcut (listed in settings > shortcut > Text Editor
). Open the file containing your function (in the sources
panel of the DevTools) and press:
ctrl + shift + O
or in OS X:
⌘ + shift + O
This enables to list and reach members of the current file.