Calling a Javascript Function from Console - javascript

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
Image 2 (Chrome): http://imgur.com/a/dLnRX

You can invoke it using
window.function_name()
or directly without window like
function_name()

Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

Related

window.functionName is undefined in my code while it is defined in the developer tool console

I've tried delaying the code even if I execute window.functionName in the console before the code actually finishes it, I still get the same outcome (works when I directly enter window.functionName in the console but not when being executed from the javascript code).
Note this is all happening in the content-script of a chrome extension.
For full context, I have a Vue component which has a method that calls a function in another javascript file which eventually calls window.functionName -- so something like this:
SomeVueComponent.vue
<template>
<button #click="buttonClicked">
</template>
<script>
import { doSomething } from 'do-something.js';
export default {
...
methods: {
buttonClicked() {
doSomething();
}
}
}
</script>
do-something.js
export function doSomething() {
doFunctionName() {
window.functionName(); // Returns "Uncaught ReferenceError: functionName is not defined"
}
...
whenElementIsShown() {
// When the element was shown a script was injected to the page that sets window.functionName
// to something. I tried putting doFunctionName in a timeout and got the same results.
doFunctionName();
}
}
Whereas in the developer tools console...
window.functionName() // Returns "f (){...}"
I'm just not sure why window would be different in the two cases. Is it because of Vue? Is it some scoping issue? Is there a way to get the most recently updated window?
Turns out the window variable in the chrome extension is different than the page's window variable. More info here: Chrome extension - retrieving global variable from webpage

Best Practice : Call a function from chrome dev console [duplicate]

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
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

Find What caused a js function call using chrome developer tool

In my web page, I get a "alert" that I want to know what causes it to fire and appear in page. Is it possible to use chrome developer tools to find it ?
You can bind some function of yours to window.alert;
alert = function myCustomAlert(){ console.log("caller", myCustomAlert.caller); }
You can place this at developer tools console and inspect the caller.
You can do this with other techniques like :
alert = function myCustomAlert(){ console.log("caller", arguments.callee.caller.name); }
The only problem with this is that it has to run on a non-strict scope.
Yes go the page where you are getting this alert and open developer tool and go inside "Elements" tab and do a search of text "alert"
( CTRL+F in windows or CMD+F in Mac)
. you should find the line of code which is firing the alert actual code should be something like window.alert("message which you are seeing on screen");
or alternate way is right click on page and do
"view page source"
and search of same text "alert" you should get the line of code.
Try to assign new function to a window.alert property and print stack trace using console.trace():
window.alert = (function( window ) {
var oldAlert = window.alert;
return function alert( message ) {
console.trace();
oldAlert( message );
};
})( window );
Stack trace is better than caller name because it works in strict mode and it provides more information. But this code snippet will not work if alert is called by setTimeout, setInterval or as a event handler:
// In this case stack trace consists of single alert call.
setTimeout(alert, 0, "foo");
So if this solution does not help you, you probably need to replace other functions (setTimeout, setInterval, addEventListener) in similar manner as well. For more information you can look at Long stacktraces project.

Why does prototyping Function not affect console.log?

I prototyped Function so that it has a getBody function:
Function.prototype.getBody = function() {
// Get content between first { and last }
var m = this.toString().match(/\{([\s\S]*)\}/m)[1];
// Strip comments
return m.replace(/^\s*\/\/.*$/mg,'');
};
See here for more info.
I tried to test it this way:
console.log(console.log.getBody.getBody());
but received an error: TypeError: console.log.getBody is undefined.
I figured out that maybe this happens because console.log was defined before I actually prototyped Function so I created an empty function x right before the prototyping and tried to call
console.log(x.getBody.getBody());
which worked without a problem. Checking the type of console.log with typeof console.log results in "function". Here's a CodePen to try it out. All of this wasn't really a surprise since it's what I expected except of console.log.getBody to be undefined.
So why does prototyping Function not affect console.log? I'm using Firefox 18.0.1 with Firebug 1.11.1.
This seems to be an issue with Firebug not with Firefox per se. My guess is that Function in Firebug lives in a different scope then Function in your page. (since unlike the other browsers Firebug is an extension , not a built in browser tool)
In fact if instead of Firebug you use the built in Firefox console (Ctrl+Shift+K), your code works perfectly fine.
More information about Firebug internals can be found here
http://getfirebug.com/wiki/index.php/Firebug_Internals
This excerpt may be interesting
When Firebug is detached from Firefox, open in a new or separate
window, the new window has its own scope. In that scope, a few Firebug
script tags compile to create a connection back to the original
browser.xul window. Most important, chrome.js is unique to each top
level window, but the Firebug object used by the detached window is
the object of the parent browser.xul.

firefox / chrome console log of functions

Normally I use ff + firebug and I find extremely useful it's console feature: if you console.log(a_function); you don't see the (IMHO totally useless) function body, but a link to the js source file where the function is defined.
(On https://getfirebug.com/logging they describe it in the "Logging object hyperlinks" paragraph)
but but, is there a way to have the same behaviour on the firefox / chrome "native" console?
You could add console.trace() or even console.log() within the function definition to track it. Something like this:
function something(){
var x = 5 +3;
console.trace();
console.log("FUNCTION SOMETHING");
return x;
}
So, when it shows up in your Chrome console tools, you can see the originating file and line AND click on it to get to that file's source. Not as eloquent as FF Firebug, but it's a start.
I don't know if you have access to these functions and just want an easy way of going from the console to the source file OR truly don't know where the function originates. But this is what I would do. Check out the source for reference!
Source: https://developers.google.com/chrome-developer-tools/docs/console-api#consoletrace
In Chrome if you place your function in the console.dir function, you will get additional information about the function. You can then right click on the function and select "show function definition".
Example:
console.dir(my_function);
I'm not seeing anything in firefox.
Try to use
console.log("test");
It will work on both ff and chrome.
why not console.debug(yourfunc.toString()); ?

Categories

Resources