Where does JSFiddle store my variables? - javascript

Introductory comments: As an experiment, I'm debugging some code with JSFiddle. I have no trouble adding debugger; statements or displaying stuff in alert(); windows. My problem is with the Chrome Console: I'd like to use it to print out the values of variables.
Illustrative example: On JSFiddle, I put the following code in the JavaScript box.
var sampleVar = "test value";
After the code has run, it seems that I have no way of viewing the variable values. I can view them before the program's run to completion, by adding a debugger; statement and evaluating sampleVar on the console. (As shown by this (ridiculously simple) JSFiddle and this screenshot.)
Further extrapolation: But I'd like to be able to open up the complete program and probe through it's variables. Is there a way for me to do that? I tried opening up the console and evaluating sampleVar but it appears to be undefined on the top-level scope. (As shown in this screenshot.)
Restatement of question Where is JSFiddle putting my variables? How do I access them?
Postscript: Sorry for linking to imgur, I thought adding the pictures directly would distract from the question.
Notable comparison: Contrast this difficulty debugging JSFiddle with the ease of debugging JSBin. If I open a "Console" frame in JSBin I can recall the variables I declared in my code, no problem.

Where is JSFiddle putting my variables? How do I access them?
It's putting it where you're telling it to. JSFiddle defaults to put all your code in a window.onload function which means everything you declare with var is local to that callback. (You can of course set properties on window explicitly). Here is such an example.
This setting is changeable from the left hand menu - if you move it to head or body you will have access to them from the developer tools. Moreover, it's worth mentioning that if you invoke the debugger while that code is running you will have access to those variables even if they are in a closure.

The code is evaluated in an iframe on a different domain (fiddle.jsshell.net). This is done for security reasons.
edit: In Firebug, you can use cd(document.querySelector('iframe').contentWindow);, in Chrome you can use the dropdown next to the filter icon to switch frames.

Related

Why can I not inspect javascript variables when paused on a Svelte breakpoint

This is Svelte-specific.
In either Chrome or Edge DevTools, when pausing on a breakpoint on some line of javascript between script tags, we can inspect variable values in the Watch list. But when I place a breakpoint on an area of the body where Svelte is handling DOM-generation, none of my component's variables are inspectable. They all say "not available". This makes it really hard to debug a problem our #if/#each, etc.. type blocks. See pic below. Why is this happening, and what can I do to see these variable values as they are being processed by Svelte's #each command?
The compiled output of Svelte files is vastly different than the source. Setting breakpoints in the source relies on source maps which try to map the output back to the source location, but there is no guarantee that any of the variables exist or are named the same.
E.g. you will often see ctx[0], ctx[1], etc. in the output as that stores the component state. Personally, I disable source maps for that reason and work directly with the output. That is a bit inconvenient but you see exactly what the code is.
You can turn source maps off in the settings.
Or open the command palette (something like Ctrl + Shift + P) and type source maps to find a command to toggle it.
The source file should also have a button that lets you jump to the compiled output, if you just want to look at it temporarily to see what is there. I think it is somewhere in the status bar at the bottom.
You can also check the Scope section in the same sidebar as Watch. It also shows all variables that are currently in scope. You may have to extend various parent scopes. E.g. you can see a create_each_block function in your screenshot.

How to programmatically get the HTML that the Devtools see when clicking on line number?

I'm trying to build a logic that resolves to line number and I attempt to get copy of html this way,
let HTMLdoc = new XMLSerializer().serializeToString(document)
console.log(HTMLdoc)
But I see that it's output different to the one I see on Devtools when clicking on the error stack's line number.
function foo () {
let stackTrace = (new Error()).stack;
console.log(stackTrace);
}
foo();
You can click Run Code Snippet and open Devtools, then click on the line number you see and Devtools will open the document.
You will find that the Devtools opened document lack CSS and other Div elements.
How do I grab the same one that Devtools gets?
Related
My current hypothesis is that Devtools avoid displaying externally loaded ones. I could be wrong.
If my hypothesis is correct, I need to figure out a regular expression that replaces the externally loaded ones.
serializeToString(document) will serialize the current document state, including all the changes that may have been applied at runtime. In this case, additional styles were added after the page has been rendered but there may be more drastical changes too that completely remove or redorder things.
When you look at the stack trace from JavaScript, then the browser’s JavaScript engine will attempt to give you information that is closely related to the original source since that’s where your code is coming from. If you use source maps with minified code, the browser is usually even able to tell you where a particular thing came from in the original unminified code even if that code does not even closely match the code that is being executed (e.g. when using a transpiler).
In the end, you cannot really figure out what the browser will tell you where the line of code came from just by looking at the document at runtime. If your code follows very strict rules, you may be able to estimate this with some calculations but this isn’t a safe approach.

How to detect where JavaScript alert is coming from?

I am trying to debug a very complex IE Intranet application. I am getting an alert with a custom message stating that an exception has occurred. I would like to find out more information about this exception as the message is not very helpful.
There is a master page which contains a lot of iFrames (and .htc files if that makes a difference) so I don't think that I can try and hijack window.alert. My last resort will be to try my luck with a file search.
Using IE 8, is there anyway I can detect where this alert is coming from? The ideal solution would be to somehow create a "breakOnAlert" function which inserts a debbuger statement at the correct alert location.
To clarify: The master page contains many iframes and I believe that the error+alert is coming from one of these. Each iframe is an aspx page (sometimes with dynamic html/javascript from the user) and contains inline and external JavaScript. Before posting I did try overriding alert in my page (a child page inside an iframe) but it didn't work. I am assuming that It doesn't work as each iframe has their own window object so they each have their own version of alert. For this to work I would need to find all iframes and override it for each one, something which I think would be very complicated to do. In the IE developer tools I can see a huge amount of script files (inline and external), so it would be very difficult to manually look for the alerts in there.
Since it's a real chore to do it in all iframes, I'd probably use Fiddler and programatically replace alert( with something like:
(function(n){alert(n);debugger;})(
IE should support the debugger statement, so you'd have a call-stack
This page explains how to do a text-replace in Fiddler
Example Fiddler custom rule to add to OnBeforeResponse:
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html"))
{
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
oBody = oBody.replace(/alert\(/gi, "(function(n){alert(n);debugger;})(");
oSession.utilSetResponseBody(oBody);
}
Ovveride alert function and set a breakpoint inside, then you can watch Stack Trace :)
function alert(message) {
var x = 'whatever';
}
$(function () {
alert('test');
});

Can't get a Javascript function named "switch" to execute

I have a simple script that should cause one of three divs to be visible while the other two are not. The function that does the work is called like so:
onchange="switch(this);"
Firebug indicates that there is an error with this text:
Javascript Error: missing { before switch body
The erroneous code it indicates is line one of my .php file where the doctype is defined like so:
<!doctype html>
The funny thing here is that I have another page with the same doctype and a script that is virtually identical which works 100%. The only differences between the two pages are that in the one that does work, I call the script from
One more thing about the Firebug output: On the page that works, the firebug script window shows the javascript like so:
function onclick(event) {
switch(this);
}
Now, on the page where the script doesn't work, Firebug shows no output that has anything to do with onchange, onclick, or anything else. It just shows the code from my javascript file and tells me I am missing the opening bracket to the function when it is clear as day that it's there. Perhaps, even with the script in the head of my main php file, something odd is happening with scope, making the defined function invisible to the callers. Any ideas?
1: why would Firebug tell me the error is on line 1 where the doctype is defined when the function that fails isn't even in the same file?
2: Does the doctype effect the way that javascript runs, and how do I debug it if it does?
I would prefer to continue using only HTML5 for this project and use a javascript file for backwards compatibility. Any help is very welcome!
P.S. I am running Ubuntu 11.10 with Apache2, PostgreSQL, and PHP5. Everything works perfectly outside of this one javascript issue.
EDIT: Totally stupid question, but I guess these things happen sometimes. As stated in the answers, switch is a keyword in Javascript and changing the name of my function fixed the problem. I really should have noticed that since my editor highlights keywords in brown...
I am not deleting this post (unless someone else suggests I do) in case someone else out there runs into the same problem. I am giving the answer to the guy who answered it first because his answer also explained the reason why I was getting the error messages I was getting, which is probably more helpful in the long run than a simple awareness of switch statements.
This error has nothing to do with your doctype or HTML5. It occurs because switch is a reserved word used for switch statements; you cannot name a function switch.
So when you do switch(this) the JavaScript engine is expecting you to follow that up with the rest of the switch statement, including the opening {, the switch body, and then the closing }. When you don't do that, it throws the given error.
The error is on "line 1" because you used an inline event handler, which in Firebug's mind is a JavaScript file with one line---that line simply being switch(this);. Firebug does not deal in line numbers of HTML files, only those of JavaScript files---whether they be real JavaScript files, or "virtual" ones generated by inline event handlers.
switch is a keyword in javascript, rename your function to something else like myswitch.
switch is a keyword in Javascript

Firefox sidebar calling javascript functions in main browser window

I'm trying to put together a quick Firefox sidebar for internal use only.
I'm struggling a bit in understanding how sidebar and main browser window communicate. What I want to do exactly is call existing javascript functions that reside in the main browser window only.
My code looks like this;
ff-sidebar.xul
<checkbox label="Button hover" checked="false" oncommand="add_enhance(this)"/>
ff-sidebar.js
function add_enhance(cb){
if (cb.checked) {
// this bit is wrong I know
window.content.document.NEWSTYLE.buttonHover();
}
}
So the question is, how do I call a function called NEWSTYLE.buttonHover() that lives in the main window?
Theoretically, this should work:
window.content.NEWSTYLE.buttonHover();
window.content points to the browser content window and the variable NEWSTYLE is defined on this window. In reality things are a bit more messy due to security mechanisms - privileged code cannot access objects of unprivileged code directly. Instead you get to access them through XPCNativeWrapper (see https://developer.mozilla.org/en/XPCNativeWrapper). Technical details changed somewhat in Firefox 4 but essentially it is still the same.
The easiest way to do what you want without introducing security issues is changing the location of the content window to a javascript: URL. Like this:
window.content.location.href = "javascript:void NEWSTYLE.buttonHover()";
You won't be able to get the result of this function but it doesn't look like you need it.

Categories