Setting breakpoints dynamically at runtime in Javascript - javascript

Both firebug and the built in console in webkit browsers make it possible to set breakpoints in running Javascript code, so you can debug it as you would with any other language.
What I'm wondering is if there is any way that I can instruct firebug or webkit that I'd like to set a breakpoint on line X in file Y at runtime, and to be able to examine variables in the specific scope that I have paused in.
I need something that can work in both Chrome (or any other webkit browser) and Firefox. For the latter Firebug is an acceptable dependency. Supporting IE is not a requirement.
I've been building an in-browser IDE ( quick video for the interested: http://www.youtube.com/watch?v=c5lGwqi8L_g ) and want to give it a bit more meat.
One thing I did try was just adding debugger; as an extra line where users set them, but this isn't really an ideal solution.

I'd say you can definitely do this for webkit browsers using the remote debugging protocol. This is based on a websocket connection and a json message protocol that goes back and forth.
You can read the announcement and the whole protocol schema.
Chrome also offers more information about this inside its remote developer-tools docs.
For the debugger domain, for instance, you can see how you can use Debugger.setBreakpoint, Debugger.setBreakpointByUrl and Debugger.setBreakpointsActive to work with breakpoints.
On the other hand, Mozilla also seems to be working on this as you can see in https://developer.mozilla.org/en-US/docs/Tools/Debugger-API and https://wiki.mozilla.org/Remote_Debugging_Protocol though I don't know the completion status of it.
In this case, you can work with breakpoints using the Debugger.Script APIs setBreakPoint, getBreakPoint, getBreakpoints, clearBreakpoints and clearAllBreakpoints
I hope this helps you move forward.

There isn't such a thing, at least not using the public, scriptable side of JavaScript. It would be possible if you have a privileged browser extension that could do that for you. For example, Firebug has a debug method which you can call from its command line, but not from scripts inside a page.
So, you have two solutions:
Implement your own JavaScript interpreter, which you can control as you wish. Might be a bit too ambitious, though...
Rely on a browser extension that can set breakpoints anywhere in the code, expose some API to public code, and interact with it from your JavaScript. But that means that users will have to install some extra piece of software before they can use your "Web IDE".

Use _defineSetter__ to watch variables, and combine it with a call to debugger when an assignment happens.
__defineSetter__("name", function() { debugger; });
or defineProperty:
function setter () { debugger; }
Object.defineProperty(Math, 'name', { set: setter });
References
MDN: Object.defineProperty
A List Apart: Advanced Debugging With JavaScript
JavaScript Getters and Setters

Related

should I use a js function other than console.log(message)?

I would like to use console.log(message) to write out some information to the browser console. However, I came across this url which seems to recommend against it:
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
Are you currently choosing to use console.log(message) as part of your js code? If not then have you identified an alternative?
I agree with Mike C above-- console is generally available in most browsers, but you should probably remove console logs before a site gets pushed to production.
Additionally, some older browser might not have the console, and if you did accidentally leave in a console log, it would fire an error when it attempted to interact with with something that wasn't defined. As an extra failsafe, you can declare console and console.log in the global namespace if they are not detected, just in case:
if (!console) {
console = {
log: function () { //noop }
};
}
should I use a js function other than console.log(message)?
simple answer is yes, But also the console.log(message) is usaually used for testing purposes and for other relevant intentions like letting other developers interract with your js source code in some sort.
However.
You should not use it to log very important messages as this could be a hole your application presumably.
Hope it helps.
While the console object is not defined in the official Javascript standard, it is specified in:
Google Chrome
Mozilla Firefox
Internet Explorer 9+
Opera
Safari
Node.js
PhantomJS (since it uses V8 like Chrome and Node.js)
and more, I'm sure. As long as you're debugging in any of the environments which supports it, you're fine. You should be removing your logging statements before pushing to production anyway so as long as it works for debugging, it's nothing to worry about.

how do you allow javascript communications with Flex/Flash/Actionscript

Well here's a problem.
I've got a website with large javascript backend. This backend talks to a server over a socket with a socket bridge using http://blog.deconcept.com/swfobject/
The socket "bridge" is a Flex/Flash .swf application/executable/plugin/thing for which the source is missing.
I've got to change it.
More facts:
file appExePluginThing.swf
appExePluginThing.swf Macromedia Flash data (compressed), version 9
I've used https://www.free-decompiler.com/flash/ to decompile the .swf file and I think I've sorted out what's the original code vs the libraries and things Flash/Flex built into it.
I've used FDT (the free version) to rebuild the decompiled code into MYappExePluginThing.swf so I can run it with the javascript code and see what happens.
I'm here because what happens isn't good. Basically, my javascript code (MYjavascript.js) gets to the point where it does
window.log("init()");
var so = new SWFObject("flash/MYappExePluginThing.swf"", socketObjectId, "0", "0", "9", "#FFFFFF");
window.log("init() created MYappExecPluginThing!!!");
so.addParam("allowScriptAccess", "always");
log("init() added Param!!");
so.write(elId);
log("init() wrote!");
IE9's console (yeah, you read that right) shows
init()
created MYappExecPluginThing!!!
init() added Param!!
init() wrote!
but none of the debugging i've got in MYappExePluginThing.as displays and nothing else happens.
I'm trying to figure out what I've screwed up/what's going on? Is MYappExePluginThing.as running? Is it waiting on something? Did it fail? Why aren't the log messages in MYappExePluginThing.as showing up?
The first most obvious thing is I'm using FDT which, I suspect, was not used to build the original. Is there some kind of magic "build javascript accessible swf thing" in FlashBuilder or some other IDE?
First noteworthy thing I find is:
file MYappExePluginThing.swf
MYappExePluginThing.swf Macromedia Flash data (compressed), version 14
I'm using Flex 4.6 which, for all I know, may have a completely different mechanism for allowing javascript communication than was used in appExePluginThing.swf
Does anyone know if that's true?
For example, when FDT runs this thing (I can compile but FDT does not create a .swf unless i run it) I get a warning in the following method:
private function init() : void
{
Log.log("console.log", "MYappExePluginThing init()");
//var initCallback:String = Application.application.parameters.initCallback?Application.application.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
var initCallback:String = FlexGlobals.topLevelApplication.parameters.initCallback?FlexGlobals.topLevelApplication.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
try
{
ExternalInterface.addCallback("method1Callback",method1);
ExternalInterface.addCallback("method2Callback",method2);
ExternalInterface.call(initCallback);
}
catch(err:Error)
{
Log.log("console.log", "MYappExePluginThing init() ERROR err="+err);
}
}
I got a warning that Application.application was deprecated and I should change:
var initCallback:String = Application.application.parameters.initCallback?Application.application.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
to:
var initCallback:String = FlexGlobals.topLevelApplication.parameters.initCallback?FlexGlobals.topLevelApplication.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
which I did but which had no effect on making the thing work.
(FYI Log.log() is something I added:
public class Log{
public static function log(dest:String, mssg:String):void{
if(ExternalInterface.available){
try{
ExternalInterface.call(dest, mssg);
}
catch(se:SecurityError){
}
catch(e:Error){
}
}
trace(mssg);
}
}
)
Additionally, in MYjavascript.js MYappExePluginThing_init looks like this:
this.MYappExePluginThing_init = function () {
log("MYjavascript.js - MYappExePluginThing_init:");
};
Its supposed to be executed when MYappExePluginThing finishes initializing itself.
Except its not. The message is NOT displaying on the console.
Unfortunately, I cannot find any references explaining how you allow javascript communication in Flex 4.6 so I can check if I've got this structured correctly.
Is it a built in kind of thing all Flex/Flash apps can do? Is my swf getting accessed? Is it having some kind of error? Is it unable to communicate back to my javascript?
Does anyone have any links to references?
If this was YOUR problem, what would you do next?
(Not a full solution but I ran out of room in the comment section.)
To answer your basic question, there's nothing special you should need to do to allow AS3-to-JS communication beyond what you've shown. However, you may have sandbox security issues on localhost; to avoid problems, set your SWFs as local-trusted (right-click Flash Player > Global Settings > Advanced > Trusted Location Settings). I'm guessing this not your problem, though, because you'd normally get a sandbox violation error.
More likely IMO is that something is broken due to decompilation and recompilation. SWFs aren't meant to do that, it's basically a hack made mostly possible due to SWF being an open format.
What I suggest is that you debug your running SWF. Using break-points and stepping through the code you should be able to narrow down where things are going wrong. You can also more easily see any errors your SWF is throwing.
Not really an answer, but an idea to get you started is to start logging everything on the Flash side to see where the breakage is.
Since you're using IE, I recommend getting the Debug flash player, installing it, then running Vizzy along side to show your traces.
Should give you a good idea of where the app is breaking down.
Vizzy
Debug Player

Get attributes in javascript

I get an element by id, and I would like to know all attributes of the object.
I've using alerts for all this kind of stuff, is that the way its done in javascript? In AS3 or whatever, I would place a break point, and investigate the object in the variables panel.
Second, if that is the way its done, how can I show ALL attributes, if I don't know what they are in advance, and show them in alert boxes? Using jquery 1.5. Thanks
If by "attributes", you mean the "properties" of the DOM node, then use...
console.dir(element);
...in Chrome's developer tools, or Firebug for Firefox.
This will allow you to expand the Object and fully inspect all of its properties, including the .attributes property.
Debugging with alerts will slowly drain your soul out through your nose. Luckily, there is a better way.
The Javascript console in a modern browser (like Chrome or Safari, or with the Firefox extension Firebug) is awesome.
You can also set breakpoints in the script tab, or from the code via the debugger statement. You can inspect globals and local variables in the scripts tab as well. It's seriously awesome.
Checkout the chrome dev tools videos for way more awesome: http://code.google.com/chrome/devtools/docs/videos.html
You have a few options:
console.log(domElement);
That'll let you log statements and view the item as it exists after your script runs. Note though that Firebug treats the object as live, so changes to the object reflect in your log statement (you'll see the actual object in your log, not just a bunch of strings) at least, it did the last time I used it).
debugger;
That'll let you pause execution and analyze your object via watch window in Firebug or Chrome dev tools, or even in IE9's developer tools.

Silverlight 4 MVVM: Call Javascript function from viewmodel

we have developed an Intranet Management Application with Silverlight 4. We have been asked to add the functionality to call a remote desktop tool which is installed on clients using the Intranet SL App. In an earlier version of the tool written in ASP.NET we just added a Javascript function to the aspx page like this:
function RunShellCommand()
{
var launcher = new ActiveXObject("WScript.Shell");
launcher.Run("mstsc.exe");
}
and called it from ASP.NET.
Now it's clear that SL4 is running in a sandbox and that I cant use the AutomationFactory to create a WScript.Shell object (out of browser mode is not an option).
I thought I could circle around the problem by, again, adding the RunShellCommand javascript method in the aspx page where the SL4 control is hosted and call it via
HtmlPage.RegisterScriptableObject("Page", this);
HtmlPage.Window.Invoke("RunShellCommand", "dummydata");
from my ViewModel. When I run the Application the debugger just skips the RegisterScriptableObject method and quits. Nothing happens.
My question is if am doing something wrong or if this just wont work this way.
Is it possible that I cant do a RegisterScriptableObject from a viewmodel?
EDIT: When I explicitly put a try, catch block around the two methods I get an ArgumentException from the first method stating that the current instance has no scriptable members. When I delete the first method and only run the Invoke, I get a browser error stating that the automation server cant create the object. So is there really no way (except OOB mode) to do this?
Yes, the explanation is correct: you should add at least one method with the ScriptableMember attribute in order that you can use the RegisterScriptableObjectmethod. But it is used only for calling C#-methods from JavaScript.
As far as I see, you want to do the opposite: to call JavaScript code from the Silverlight application. Then you need only one line:
HtmlPage.Window.Invoke("RunShellCommand");
The error automation server cant create the object has nothing to do with Silverlight. I'm sure that if you call the JS function directly - the error will remain.
According to the internet, the reason might be not installed Microsoft Windows Script. Or it is because of security restrictions of the browser.

JavaScript: Possible uses for #debug directive?

Where I work, all our JavaScript is run through a compiler before it's deployed for production release. One of the things this JavaScript compiler does (beside do things like minify), is look for lines of code that appear like this, and strip them out of the release versions of our JavaScript:
//#debug
alert("this line of code will not make it into the release build")
//#/debug
I haven't look around much but I have yet to see this //#debug directive used in any of our JavaScript.
What is it's possible usefulness? I fail to see why this could ever be a good idea and think #debug directives (whether in a language like C# or JavaScript) are generally a sign of bad programming.
Was that just a waste of time adding the functionality for //#debug or what?
If you were using a big JavaScript library like YUI that has a logger in it, it could only log debug messages when in debug mode, for performance.
Since it is a proprietary solution, we can only guess the reasons. A lot of browsers provide a console object to log various types of messages such as debug, error, etc.
You could write a custom console object is always disabled in production mode. However, the log statements will still be present, but just in a disabled state.
By having the source go though a compiler such as yours, these statements can be stripped out which will reduce the byte size of the final output.
Think of it as being equivalent to something like this:
// in a header somewhere...
// debug is off by default unless turned on at compile time
#ifndef DEBUG
#define DEBUG 0
#endif
// in your code...
var response = getSomeData({foo:1, bar:2});
#if DEBUG
console.log(response);
#endif
doStuffWith(response);
This kind of thing is perfectly acceptable in compiled languages, so why not in (preprocessed) javascript?
I think it was useful (perhaps extremely useful) back a few years, and was probably the easiest way for a majority of developers to know what was going on in their JavaScript. That was because IDE's and other tools either weren't mature enough or as widespread in their use.
I work primarily in the Microsoft stack (so I am not as familiar with other environments), but with tools like VS2008/VS2010, Fiddler and IE8's (ugh! - years behind FF) dev tools and FF tools like firebug/hammerhead/yslow/etc., peppering alerts in your JavaScript isn't really necessary anymore for debugging. (There's probably a few instances where it's useful - but not nearly as much now.) Able to step through JavaScript, inspect requests/responses, and modify on the fly really makes debugging alert statements almost obsolete.
So, the //#debug was useful - probably not so much now.
I've used following self-made stuf:
// Uncomment to enable debug messages
// var debug = true;
function ShowDebugMessage(message) {
if (debug) {
alert(message);
}
}
So when you've declared variable debug which is set to true - all ShowDebugMessage() calls would call alert() as well. So just use it in a code and forget about in place conditions like ifdef or manual commenting of the debug output lines.
For custom projects without any specific overridden console.
I would recommend using: https://github.com/sunnykgupta/jsLogger , it is authored by me.
Features:
It safely overrides the console.log. Takes care if the console is not available (oh yes, you need to factor that too.)
Stores all logs (even if they are suppressed) for later retrieval.
Handles major console functions like log, warn, error, info.
Is open for modifications and will be updated whenever new suggestions come up.

Categories