Find JavaScript function definition in Chrome
Asked Answered
C

13

339

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.

Curassow answered 22/3, 2012 at 19:7 Comment(3)
There is a search bar that greps the current file in the Scripts tab and you can peek at the contents of a function by printing it. But I am now curios if there is a way to do a more general search like you want...Valvule
With the Google Chrome Developer Tools, at the "Sources" Tap -> right window you have to possibility to set "Event Breakpoints".Godin
In my case I had a variable set to an unknown function. I did myvar.toString() and it printed: "function Object() { [native code] }" which is all I needed to know.Upholsterer
G
410

Lets say we're looking for function named foo:

  1. (open Chrome dev-tools),
  2. Windows: ctrl + shift + F, or macOS: cmd + optn + F. This opens a window for searching across all scripts.
  3. check "Regular expression" checkbox,
  4. search for foo\s*=\s*function (searches for foo = function with any number of spaces between those three tokens),
  5. 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.

Glade answered 6/6, 2012 at 10:21 Comment(12)
This is only one way to define a function named foo. There are others. What if our function is e.g. bar['foo']? (There's no good answer to that question, as far as I know --- it's essentially "don't write convoluted code")Jakoba
add the OS X shortcut in the answer or explicitely specify what platform ctrl-shift-f is meant forDesdamonna
@zplesivcak I don't know to what platforms <kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>F</kbd> appliesDesdamonna
I couldn't find "function definition" using the selected answer. I have searched on Google and couldn't find any help. (Using Chrome Version 41.0.2272.118 m )Bandsman
And then you fail to find function declarations, dynamically generated function expressions and anonymous (unnamed) functions. I'd rather want something like Firefox: Click the function reference in the watch panel -> Jump to the function reference.Birdsong
In Chrome 46.0.2490.86 m under Windows 10 I had to double-escape the special characters in the regex, e.g., foo\\s*=\\s*functionTammany
@FagnerBrack There's no perfect solution that I'm aware of, and Chrome now has functionality like that too, but the reference has to exist in scope when you're searching for it for that trick to work. I think this regex handles the situations you mentioned (except anonymous functions, which.. I mean, just search for "function" if you want to see them): ^(?=.*foo)(?=.*function).*$ Also, the answer above is technically a perfect answer to the question, with some bonus info thrown in.Blueberry
Note the regex above won't find arrow functions assigned to a variable like var foo = () => (...), but that should be pretty rare. @StevenLu This is pedantic, but I believe the function is not named foo in your second example. It's assigned to the foo property on bar.Blueberry
This doesn't work as the function is either not defined that way or is not coming up in search, as just searching for the function name shows only 1/1 result which is only in the HTML tag onclick call (no matter where or how I search from). I'm not sure how to find this function's definition without scouring every included .js file, which I thought were already included in this kind of search.Vullo
The answer seems to be outdated, nothing happens if I click that key combination in the developer console.Prosser
Correct @Black, nothing happens, it is an old answer and Chrome moved on.Acidic
Re the outdated comments above: I'm using the latest version of Chromium and CTRL + SHIFT + F still does workHessian
H
92

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:

 Chrome Dev Tools > Console > Show Function Definition

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!

Hemitrope answered 16/1, 2013 at 11:4 Comment(12)
Is there a shortcut or a function which will allows to search by a function reference? like ">inspect(document.body)". For now I have to d > tmp={a:myFunc}; >tmp, followed by the "Show function definition"Mcshane
I think you can do dir(myFunc)Hemitrope
dir(myFunc) is much better, but still need two clicks and mouseMcshane
Oh, you mean if you can do it completely from keyboard? Something like findDefinition(myFunc)? AFAIK that doesn't exist yet...Hemitrope
If you don't have an object containing the function, you can create an object around it and it will still work. E.g. in the console type: ({1:somefunction}), then right click the function inside the printed object.Kraul
@Protectorone you can just type dir(someFunction) into the consoleHemitrope
@DP Yes, but that will just show the definition, not take you to where it is actually defined. The latter is more useful, because you can live edit it.Kraul
@Protectorone no, console.dir() always prints its argument as on object with properties so you can right-click on it and select "Show function definition"Hemitrope
There's no object in my case, all I have is HTML: onclick=some_function(weird). The only search result no matter what I try just shows the HTML tag, though the function is doing... something... and isn't a pre-defined JavaScript function.Vullo
You should be able to inspect the element, then go to DOM Listeners in the right panel and find the click handler there. You can also use the Visual Event Chrome extension to make searching for the right handler faster.Hemitrope
Oddly, clicking show function definition does nothing for me. Non-responsive.Corrade
I wonder if that function got garbage-collected by the time you're trying to inspect itHemitrope
B
56

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.

Barely answered 22/3, 2012 at 19:14 Comment(5)
@futzlarson When I do this, the source and line is printed clear to the right on the same line as the function's closing brace.Marney
This works for finding the currently active definition of the function.Aplite
Unfortunately this no longer works, as of at least a couple months ago. Instead you just get a very unhelpful function unknownFunc(unknown) line now, with no inline code.Remunerate
@Remunerate At least in Chrome 45, this works again. I'm aware that things changed somewhere inbetween when this was posted and now. Conclusively, it seems to work again.Barely
This merely shows 'undefined' even though clicking the button that calls the function does stuff from some source code I can't find anywhere... is there some magical scope wizard waving his wand somewhere and how do I find him?Vullo
B
39

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.

Brattishing answered 10/7, 2016 at 15:52 Comment(8)
well, what this seems to do is not "go to definition" of an arbitrary function call, but "show you all the function names in the current file and let you go to them" - which is kinda useful too.Watery
This is exactly what I was looking for, a feature similar to firefox! In firefox you can simply open the dev tools, hit Ctrl+f, and it will search for the JS function in all panes(HTML/CSS/Javascript/etc.). This does it, unlike the regex features mentioned in other answers.Superabound
@Randy, on which version of chrome? Which OS? I use Chrome Version 59.0.3071.115 on OS X and it works fine.Brattishing
@Brattishing Sorry, I did not realise you had to be in sources for this to work. I expected it to work in the console as well.Vibrio
For me a chrome menu opens if I press that key combination in the dev console.Prosser
@Prosser Just to make sure: 1. Focus (click) on the source files where you want to look for the function, in the source panel of the dev tools. 2. It's the letter 'O', not the number '0'.Brattishing
Is it the case that the "go to member" functionality only searches through sources that are currently opened in a Dev Tools tab? I just searched a function that couldn't be found, but after opening the source in which it is defined (using the evaluate, mouse-click method…), it was able to find it.Kraul
@Protectorone, yesBrattishing
H
20

Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.

Hemiterpene answered 4/12, 2013 at 13:9 Comment(0)
P
19

Different browsers do this differently.

  1. First open console window by right clicking on the page and selecting "Inspect Element", or by hitting F12.

  2. In the console, type...

    • Firefox

      functionName.toSource()
      
    • Chrome

      functionName
      
Piano answered 20/11, 2015 at 6:7 Comment(3)
the function I'm searching for is stop() and it is used as onmouseover="this.stop();" when I do what you say, it returns: stop() { [native code] } So what to do now?Stew
functionName.toSource() also works on latest chrome versions.Runty
@Stew Look at the online documentation for the builtin stop.Sponger
I
9

in Chrome console:

debug(MyFunction)
MyFunction()
Irreparable answered 7/12, 2018 at 15:24 Comment(2)
I like that. Noteworthy: do a undebug(MyFunction) to remove the breakpoint again (after you found the method implementation)Lepore
On Edge Developer tool, one doesn't have to write debug. Just enter the function name on console. On the console itself it shows the function body, just click on that it takes you to the function.Whiteley
S
6

I find the quickest way to locate a global function is simply:

  1. Select Sources tab.
  2. In the Watch pane click + and type window
  3. Your global function references are listed first, alphabetically.
  4. Right-click the function you are interested in.
  5. In the popup menu select Show function definition.
  6. The source code pane switches to that function definition.
Sentimental answered 25/12, 2017 at 13:1 Comment(0)
C
5

I had a similar problem finding the source of an object's method. The object name was myTree and its method was load. I put a breakpoint on the line that the method was called. By reloading the page, the execution stopped at that point. Then on the DevTools console, I typed the object along with the method name, i.e. myTree.load and hit Enter. The definition of the method was printed on the console:

enter image description here

Also, by right click on the definition, you can go to its definition in the source code:

enter image description here

Cormac answered 5/5, 2020 at 15:36 Comment(0)
F
2

In Google chrome, Inspect element tool you can view any Javascript function definition.

  1. Click on the Sources tab. Then select the index page. Search for the function.

enter image description here

  1. Select the function then Right-click on the function and select "Evaluate selected text in console."

enter image description here

Fulks answered 26/8, 2019 at 4:41 Comment(0)
P
0

If you are already debugging, you can hover over the function and the tooltip will allow you to navigate directly to the function definition:

Chrome Debugger Function Tooltip / Datatip

Further Reading:

Prerecord answered 11/1, 2020 at 19:27 Comment(0)
S
0

You encounter VM defined JS function ,you can try this command in Chrome console panel below. Like this: foo function name is window.P.execute

>window.P.execute.toString()
<'function(d,h){function n(){var a=null;e?a=h:"function"===typeof h&&(p.start=w(),a=h.apply(f,wa(d,k,l)),p.end=w());if(b){H[d]=a;a=d;for(da[a]=!0;(z[a]||[]).length;)z[a].shift()();delete z[a]}p.done=!0}var k=g||this;"function"===typeof d&&(h=d,d=E);b&&(d=d?d.replace(ha,""):"__NONAME__",V.hasOwnProperty(d)&&k.error(q(", reregistered by ",q(" by ",d+" already registered",V[d]),k.attribution),d),V[d]=k.attribution);for(var l=[],m=0;m<a.length;m++)l[m]=\na[m].replace(ha,"");var p=B[d||"anon"+ ++xa]={depend:l,registered:w(),namespace:k.namespace};d&&ya.hasOwnProperty(d);c?n():ua(l,k.guardFatal(d,n),d);return{decorate:function(a){U[d]=k.guardFatal(d,a)}}}'

so we got full function code.

Striate answered 13/6, 2022 at 1:33 Comment(0)
D
0

In Chrome Dev Tools (F12) you could also navigate to the method source from its prototype definition:

method definition prototype

Dislike answered 17/8, 2023 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.