
Friday May 16, 2008
DOM Inspector in Firefox Sidebar
In this entry I talked about how to show Google Talk in Firefox Sidebar. Using the same technique you can show the DOM Inspector in the Firefox Sidebar. That way you can get the DOM Inspector in the same window as the page you are inspecting. UPDATE: You can simply install this add-on in the Firefox browser. It will add a new menu item Tools:DOM Inspector in sidebar .
Selecting this menu item will show the DOM Inspector in the Firefox sidebar. It also makes the sidebar resizable.
Here is how. Just create a bookmark like this: 
and then invoke the bookmark. Then use the File:Inspect Window > menu item to select the window you are browsing in. You will see something like this

Unfortunately the Sidebar is not resizable. However this could be tweaked using the property overlay incantation overrding the flex attribute of the sidebar box. Also the popup dialogs to search for nodes does not work. Once again some XUL overlay gimmickry could come handy here.
Useful? You decide.
Posted by sandipchitale
( May 16 2008, 08:45:44 PM PDT ) Permalink

Sunday May 11, 2008
E4X assignment gotcha
Obscure TIP Warning E4X allows direct embedding of XML literals inside JavaScript which make it very easy to work with XML inside JavaScript. Recently while working on a Firefox extension I got bit by some unexpected behavior of an XML variable assignment operator (=). Basically it clones the XML document fragment on the right hand side of assignment operator. The following program demonstrates the behavior.
<html> <head> <title>E4X</title> <script> function e4x() { var languages = <languages></languages>; alert("initial value of variable 'languages'=:\n" + languages.toXMLString()); var javascript = <scripting>JavaScript</scripting> alert("initial value of variable 'javascript':\n" + javascript.toXMLString()); languages.scripting = javascript; alert("after adding 'javascript' variable as a child node - value of variable 'languages':\n" + languages.toXMLString()); javascript.version = <version>1.2</version> alert("after adding version node - value of variable 'javascript':\n" + javascript.toXMLString()); alert("after adding version node to variable 'javascript' - value of variable 'languages':\n" + languages.toXMLString() + "\nvalue of variable 'languages' does not reflect the changes made to the value of variable 'javascript'."); } </script> </head> <body onload="e4x();"> </body> </html>
You can try this program (if you are using Firefox) by clicking here.
Posted by sandipchitale
( May 11 2008, 07:25:00 PM PDT ) Permalink

Thursday May 08, 2008
NetBeans 6.1 and trunk compatible Code Template Tools NBMs
NetBeans 6.1 is out!
I have updated the Code Template Tools module to work with NetBeans 6.1 FCS and trunk. Here are the NBMs" NetBeans 6.1 FCS compatible Code Templates Tools NBM post 6.1 main compatible Code Templates Tools NBM I need to figure out how to publish multiple NBMs on Plugin Portal. In the mean time you will have to use these.
Posted by sandipchitale
( May 08 2008, 01:31:29 PM PDT ) Permalink

Saturday April 26, 2008
YouTube Viewer add-on project
In this blog entry I talked about the YouTube Viewer add-on for Firefox. In the last blog I talked about how to use a freeform Web NetBeans 6.1 Project to build the iPhone mode add-on for Firefox. Download a similar freeform Web NetBeans 6.1 Project for YouTube Viewer.
Posted by sandipchitale
( Apr 26 2008, 04:49:09 PM PDT ) Permalink
Using NetBeans 6.1 freeform project to build iPhone mode add-on for Firefox project.
In the last entry I talked about an iPhone mode add-on for Firefox. I used a free form Web Project of NetBeans 6.1 IDE to build the iPhone mode add-on. The NetBeans 6.1 IDE has a great JavaScript editor. That was a big plus. Here is a visual tour of the Web Project setup. The Build Script <?xml version="1.0" encoding="UTF-8"?> <project name="iPhoneEmulator" default="all" basedir="."> <description>iPhone Emulator for Firefox.</description> <property name="build.dir" value="build"/> <!-- build iphone --> <target name="-create-iphone-jar"> <echo message="Build iphone.jar"/> <mkdir dir="${build.dir}"/> <zip destfile="${build.dir}/iphone.jar"> <zipfileset dir="." includes="content/**" /> <zipfileset dir="." includes="locale/**" /> <zipfileset dir="." includes="skin/**" /> </zip> </target> <target name="-gen-manifest"> <echo message="Configuring chrome-manifest"/> <mkdir dir="${build.dir}"/> <copy file="chrome.manifest" tofile="${build.dir}/chrome.manifest" overwrite="true"/> <replaceregexp file="${build.dir}/chrome.manifest" match="^(content\s+\S*\s+)(\S*/)$" replace="\1jar:chrome/iphone.jar!/\2" flags="g" byline="true"/> <replaceregexp file="${build.dir}/chrome.manifest" match="^(skin|locale)(\s+\S*\s+\S*\s+)(.*/)$" replace="\1\2jar:chrome/iphone.jar!/\3" flags="g" byline="true"/> </target> <target name="-create-iphone-xpi" depends="-create-iphone-jar,-gen-manifest"> <echo message="Build iphone.xpi"/> <mkdir dir="${build.dir}"/> <zip destfile="${build.dir}/iphone.xpi"> <zipfileset dir="${build.dir}" includes="iphone.jar" prefix="chrome" /> <zipfileset dir="${build.dir}" includes="chrome.manifest" /> <zipfileset dir="." includes="install.rdf" /> </zip> </target> <target name="all" depends="-create-iphone-xpi"/>
<target name="run" depends="clean,all"> <exec executable="firefox" osfamily="unix"> <arg file="${build.dir}/iphone.xpi"/> </exec> <exec executable="/usr/bin/open" osfamily="mac"> <arg value="-b"/> <arg value="org.mozilla.firefox"/> <arg file="${build.dir}/iphone.xpi"/> </exec> <exec executable="C:/Program Files/Mozilla Firefox/firefox.exe" osfamily="windows"> <arg file="${build.dir}/iphone.xpi"/> </exec> </target>
<target name="-clean-iphone"> <echo message="Clean iphone"/> <delete file="${build.dir}/iphone.jar" failonerror="false"/> <delete file="${build.dir}/chrome.manifest" failonerror="false"/> <delete file="${build.dir}/iphone.xpi" failonerror="false"/> </target> <target name="clean" depends="-clean-iphone"/> </project>
Here is the rest: 

Projects and Files window showing the layout:  
The NetBeans IDE is slowly starting to take shape as a premium AJAX, Web 2.0 and Mobile development IDE.
Posted by sandipchitale
( Apr 26 2008, 12:27:54 PM PDT ) Permalink

Sunday April 20, 2008
Open Location in iPhone Mode in Firefox
I have been hacking Firefox. Here is a simple iPhone mode add-on. This is very basic mode. You can type an address in the address field and hit ENTER. You can use the Reload button to reload the page. You can use Go Back and Go Forward buttons to navigate the history. You can use Add Bookmark button to add a bookmark to the current page. You can use the Show Bookmarks button to show the Bookmarks window. Just lkie the iPhone - the address bar is hidden when the document loads. You can reshow the address bar by clicking on the battery indicator bar. Any URL can be invoked in the iPhone mode from command line by using the -iphone command line argument.
> firefox -iphone URL
Use the File:OpenLocation in iPhone Mode... menu item to launch the iPhone mode. 
 
Talk about recursive :)
Download the add-on. Download the NetBeans 6.1 project. DISCLAIMER: This add-on is experimental. So no guarantees. Use the add-on at your own risk.
Posted by sandipchitale
( Apr 20 2008, 11:51:52 AM PDT ) Permalink

Friday April 18, 2008
Nested JavaScript functions and Non-static Inner Classes in Java
I am a Java programmer and understand the Java language concepts such as inner classes and scoping rules well. I have been learning JavaScript and trying to understand the scoping rules in JavaScript. Here are some of my observations about the similarities and differences between some aspects of nested JavaScript functions and Non-static inner classes.
| JavaScript | Java | var global = 0; function outerFunction() { var outerLocal = 1; function innerFunction() { var innerLocal = 2; // Can access outerLocal here // Can access global here }
return innerFunction; }
outerFunction.staticVar = 10; // elsewhere function callingFunction() { // Get a reference to innerFunction() var refToOuterDotInner = outerFunction(); refToOuterDotInner(); }
| public class Outer() { public static int staticField = 10; private int outerLocal = 1; public class Inner() { private int innerLocal = 2;
private void innerMethod() {
int methodLocal = 4; // Can access innerLocal here // Can access outerLocal here } }
public Inner getInner() { return new Inner(); } }
// elsewhere public void callingMethod() { Outer outer = new Outer(); Inner innerInstance = outer.getInner(); // Invoke method of inner class inner.innerMethod(); }
| innerFunction() is analogous to ---------> The scope of innerFunction() maps to two concepts in Java world - the scopes of innerMethod() and the instance of Inner class. The execution call stack of innerFunction() maps to the innerMethod() though.
| innerMethod() and instance of Inner class I think this is the source of confusion for Java programmer. At least it was to me.
| Three scopes when the innerFunction is executing: - Global
- scope of outerFunction
- scope of innerFunction - maps to last two scopes on Java side
| Three scopes when innerMethod() is executing. - No equivalent in Java
- Outer instance scope
- Inner instance scope
- innerMethod() local scope
| outerLocal in outerFunction is analogous to ---------> outerLocal is private to outerLocal but can be accessed from innerFunction() .
| outerLocal field of an instance of Outer class. outerLocal is private to the instance of Outer class but can be accessed from innertMethod() .
| | In terms of scope level innerLocal is analogous to ---------> | methodLocal and innerLocal
| no analogue
| the Outer class instance can be accessed using Outer.this
| call stack involves: innerFunction() callingFunction()
| call stack: innerMethod() callingMethod()
| outerFunciton.staticVar is analogous to ---------> Note the absence of () after outerFunction.
| static access to Outer.staticField
|
The scoping and access level rules of the inner functions allow for closures (a powerful concept) in JavaScript.
Do you have any insights to share?
Posted by sandipchitale
( Apr 18 2008, 07:25:38 AM PDT ) Permalink

Sunday April 13, 2008
TIP: Making JOptionPane dialog resizable
It is a well known issue that the dialogs shown by the javax.swing.JOptionPane are not resizable. In the last blog entry there was a tip in the code about just how to make the dialogs shown by javax.swing.JOptionPane resizable. Here is the relevant snippet of code:
// TIP: Make the JOptionPane resizable using the HierarchyListener editorPane.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(editorPane); if (window instanceof Dialog) { Dialog dialog = (Dialog)window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } });
The tip works if you are using any java.awt.Component subclass as the message in javax.swing.JOptionPane. The tip works by listening to the hierarchy event on the message component, finding the java.awt.Dialog component and setting it's resizable property to true.
Posted by sandipchitale
( Apr 13 2008, 09:30:12 AM PDT ) Permalink

Saturday April 12, 2008
TIP: Displaying rich messages using JOptionPane and JEditorPane
In this and this blog entry I discussed technics to show images and multiline text in tooltips. The same technics can be applied to show rich messages using JEditorPane. Here is an example: import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dialog; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Window; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JEditorPane; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener;
public class NetBeansDay2008 { public static void main(String[] args) { // Turn anti-aliasing on System.setProperty("awt.useSystemAAFontSettings", "on"); final JEditorPane editorPane = new JEditorPane();
// Enable use of custom set fonts editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); editorPane.setFont(new Font("Arial", Font.BOLD, 13));
editorPane.setPreferredSize(new Dimension(520,180)); editorPane.setEditable(false); editorPane.setContentType("text/html"); editorPane.setText( "<html>" + "<body>" + "<table border='0px' cxellpadding='10px' height='100%'>" + "<tr>" + "<td valign='center'>" + "<img src='" + "http://www.netbeans.org/images/javaone/2008/nbday08_logo.gif" // Alternatively an image stored next to the NetBeansDay2008 // class can be used like this. //+ NetBeansDay2008.class.getResource("nbday08_logo.gif").toExternalForm() + "'>" + "</td>" + "<td>" + "<a href='http://www.netbeans.org/community/articles/javaone/2008/nb-day.html'><b>NetBeans Day</b></a><br>" + "San Francisco May 5th, 2008<br>" + "<br>" + "NetBeans - The only IDE you need!<br>" + "</td>" + "</tr>" + "</table>" + "</body>" + "</html>" );
// TIP: Make the JOptionPane resizable using the HierarchyListener editorPane.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(editorPane); if (window instanceof Dialog) { Dialog dialog = (Dialog)window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } });
// TIP: Add Hyperlink listener to process hyperlinks editorPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { EventQueue.invokeLater(new Runnable() { public void run() { // TIP: Show hand cursor SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // TIP: Show URL as the tooltip editorPane.setToolTipText(e.getURL().toExternalForm()); } }); } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { EventQueue.invokeLater(new Runnable() { public void run() { // Show default cursor SwingUtilities.getWindowAncestor(editorPane).setCursor(Cursor.getDefaultCursor());
// Reset tooltip editorPane.setToolTipText(null); } }); } else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { // TIP: Starting with JDK6 you can show the URL in desktop browser if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception ex) { Logger.getLogger(NetBeansDay2008.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } } //System.out.println("Go to URL: " + e.getURL()); } } }); JOptionPane.showMessageDialog(null, new JScrollPane(editorPane), "NetBeans Day 2008", JOptionPane.PLAIN_MESSAGE); } }
Based on a tip from a reader I have added the code to turn on anti-aliasing and use of custom set fonts in JEditorPane. This shows the following visually pleasing dialog: 
See you there!
Posted by sandipchitale
( Apr 12 2008, 08:49:54 PM PDT ) Permalink

Wednesday April 02, 2008
Mac OS Leopard: /usr/bin/open -b org.mozilla.firefox 'file:///tmp/test.html/?a=b&c=d' does not work
I just ran into a bug where by a command like this:
> /usr/bin/open -b org.mozilla.firefox 'file:///tmp/test.html/?a=b&c=d' does not work correctly. It turns out the query string such as '?a=b&c=d' does not get passed to the Firefox as evident in the address bar. The http:// protocol based URLs work correctly.
I suspect the #reference to go to a specific anchor will also not work. I have not tried it though.
This is a bug (regression) on Mac OS Leopard (10.5). It use to work on Mac OS Tiger (10.4). I have already filed a bug with Apple for this.
BTW I have to use the /usr/bin/open command to reliably and repeatedly open a URL in Firefox (i.e. when Firefox is already running or not). That is because if I use the command such as: > /Application/Firefox.app/Contents/MacOS/firefox 'file:///tmp/test.html/?a=b&c=d'
when Firefox is already running it give me an error along the lines of "There is already an instance of Firefox running. You can only run one instance of Firefox.". I thought this information may be useful to some folks who are struggling with the same issue.
Posted by sandipchitale
( Apr 02 2008, 10:28:20 AM PDT ) Permalink

Monday March 31, 2008
TIP: Using Object.prototype.toString.apply(...);
You can use Object.prototype.toString.apply(<any JavaScript
object>); displays the value returned by primordial toString()
function even if the object's constructor function overrides the
toString() function. For example (Array overrides the toString() function) : alert([1,2,3].toString()); => '1,2,3' alert(Object.prototype.toString.apply([1,2,3])); => '[object Array]' // better info than the next line alert(typeof [1,2,3]); => 'object' // does not tell it is an Array
TIP: You can evaluate expressions like the above in the Firefox's Tools:Error Console's Evaluate text field.
Posted by sandipchitale
( Mar 31 2008, 11:07:56 PM PDT ) Permalink

Saturday March 29, 2008
Notes on JavaScript functions and objects
functionsstatic (or definition) context
- All functions have a property named prototype.1 The value of prototype is an object2 with a property named constructor.3 The value of constructor is the function itself.4
- All functions have a property called length which specifies the expected number of parameters as declared in function signature.5
- The value of constructor property of a function is the function Function6. That is because, the hidden super instance of a function is the value of the prototype property of the function Function.7
execution context- While a function executes there is a special variable arguments that holds the actual arguments that were passed in when the function was invoked.
- While a function executes there is a special variable arguments which is of type Arguments which is an array-like object with a property length which gives the number of actual parameters passed in during invocation.
- The formal parameter names are really aliases of arguments object's indexed properties indexed by the ordinal number of the formal parameter.
- While a function executes there is a special variable arguments.callee holds a reference to the function object itself. Thus arguments.callee.length gives us the number of expected parameters.
- For example:
function f(p1, p2) { // p1 is alias of arguments[0] // p2 is alias of arguments[1] // you can access rest of the parameters using arguments[3] thru arguments[n] // if f was invoked like this f(10, 20, 30, 40): // the value of p1 and arguments[0] is 10 // the value of p2 and arguments[1] is 20 // the value of arguments[2] is 30 // the value of arguments[3] is 40 // the value of arguments.length is 4 i.e. four parameters were passed in // the value f.length is 2 - two parameters p1 and p2 declared in function declaration // the value arguments.callee is the function f itself. This works for anonymous functions also. // This allows writing recursive functions even in case of anonymous functions. }
Function functionstatic (or definition) context
- Function being a function has a property named prototype. The value of prototype is an anonymous function function(){} with a property named constructor. The value of constructor is the function Function.
- The value of constructor property of function Function is function Function. That is because the hidden super instance of a function is the value of the prototype property of function Function.
objects such as {} or new Object()
- The constructor of an object such as {} or new Object{} of course is function Object.8
- All objects inherit properties from a hidden super instance - the prototype object. The prototype object is the same as the value of the prototype property of function which was used to create the object using the new operator. Note: objects do not have a property named prototype.
- The inherited properties behave in a copy-on-set manner.
- All objects inherit a property named constructor from their hidden super instance - the prototype object.9
Object functionstatic (or definition) context
- Object being a function has a property named prototype. The value of prototype is an anonymous object {} with a property named constructor.10 The value of constructor is the function Object.11
- The value of constructor property of function Object is function Function. That is because the hidden super instance of a function is the value of the prototype property of function Function.
Let us say we have code like this:function Rectangle(width, height) { this.width = width; this.height = height; }
var twoByFourRectangle = new Rectabgle(2, 4);
+--------------------------------------+ inherits | +---------constructor property ----+ | +----------------------------------+ from | | | | inherits | | | v | v from v | function Function --- prototype property---> function(){} <----- function Object --- prototype property---> {constructor: Object} ^ ^ inherits | +---------------------------------------+ | from | | | | inherits | v | | from(?) function Rectangle --- prototype property ----> {constructor: Rectangle}--+ ^ inherits | from | | object twoByFourRectangle --- width property ----> 2 +--- height property --> 4
1 alert("prototype" in Rectangle); => 'true'2 alert(Rectangle.prototype); => '[object Object]'
3 alert("constructor" in Rectangle.prototype); => 'true'
4 alert(Rectangle.prototype.constructor); => '[function Rectangle]' 5 alert(Rectangle.length); => '2'
6 alert(Rectangle.constructor) => 'function Function() {[native code]}' 7 alert(Rectangle.constructor.prototype) => 'function(){}'
8 alert({}.constructor); => 'function Object() {[native code]}'
9 alert("constructor" in {}); => 'true' 10 alert(Object.prototype); => '[object Object]' 11 alert(Object.prototype.constructor); => 'function Object() {[native code]}'
TIP: You can evaluate expressions like the above in the Firefox's Tools:Error Console's Evaluate text field. Tricky huh? It was for me.
Posted by sandipchitale
( Mar 29 2008, 11:05:31 AM PDT ) Permalink

Saturday March 15, 2008
Google Talk in your Firefox sidebar
Just Create a book like this: 
Set the location to: http://talkgadget.google.com/talkgadget/client?hl=en Make sure the Load this bookmark in the sidebar is selected. Thats all!
Posted by sandipchitale
( Mar 15 2008, 09:23:50 AM PDT ) Permalink

Wednesday March 12, 2008
Remove unused binding attribute from VisualWeb JSF pages
Prior to NetBeans IDE 6.0 release VisualWeb Pages use to generate a binding attribute in the tag for every component in the page. For example, when a Grid Panel was dropped on Page1, the following tag was automatically generated in the Page1.jsp file:
<h:panelGrid binding="#{Page1.gridPanel1}" id="gridPanel1" style="height: 96px; left: 24px; top: 24px; position: absolute; width: 96px"/>
and the following field, getter and setter was generated in the Page1.java file:
private HtmlPanelGrid gridPanel1 = new HtmlPanelGrid();
public HtmlPanelGrid getGridPanel1() { return gridPanel1; }
public void setGridPanel1(HtmlPanelGrid hpg) { this.gridPanel1 = hpg; }
This was good if you wanted to access the gridPane1 component programmatically. Otherwise it only served to bloat the .jsp and .java files. Therefore starting with NetBeans IDE 6.1 (M1+) release we decided to not generate the binding
attribute automatically. Instead you can add and
remove the binding attribute (and the corresponding field, getter and setter) by invoking the action in the component's
pop up menu. For details, see the mini spec - On-demand binding attribute .
All this is well and good for projects developed using the NetBeans 6.1 (M1+) IDE and later. However the projects developed prior to NetBeanse 6.1 (M1+) IDE, do not benefit from this feature. That is where the new module - Remove unused binding attributes from VisualWeb JSF Pages comes for the rescue. This module installs the action - Remove unused binding attributes in the VisualWeb JSF Pages' in the projects pop up menu. When the action is invoked it shows a confirmation dialog:
Once you confirms the action, the unused binding attributes (and the corresponding field, getter and setter in the backing page bean) are removed from all the VisualWeb JSF pages in the VisualWeb project. The output window shows the processing messages. For example: Removing unused binding attributes for components in the VisualWeb JSF Pages in the Project '/..../NetBeansProjects/WebApplication1'... Modeling... Modeling...Done Processing '.../NetBeansProjects/WebApplication15/web/Page1.jsp' : : : Removed unused binding attribute for the component 'gridPanel1'. : : : Processing '.../NetBeansProjects/WebApplication15/web/Page1.jsp' Done
Processing '.../NetBeansProjects/WebApplication15/web/Page2.jsp' : : Processing '.../NetBeansProjects/WebApplication15/web/Page2.jsp' Done Processing '.../NetBeansProjects/WebApplication15/web/Page3.jsp' : : Processing '.../NetBeansProjects/WebApplication15/web/Page3.jsp' Done Removing unused binding attributes for components in the VisualWeb JSF Pages in the Project '/.../NetBeansProjects/WebApplication1'...Done
The process may take some time depending on the number of VisualWeb JSF pages in your project. Please make sure you have backed up your project before you invoke the action. For best results invoke the action as soon as you open the project. Aftre you have processed all you projects you can remove the module by using Tools:Plugin action. The module is available on the NetBeans 6.1 Beta Update center:
http://updates.netbeans.org/netbeans/updates/6.1/uc/beta/beta/catalog.xml.gz You can configure the update center in the Tools:Plugins:Setting tab. NetBeans 6.1 Beta IDE is required to use this module.
Please send us your feedback here. After processing, your project will become lean and mean, VisualWeb machine :)
Posted by sandipchitale
( Mar 12 2008, 08:54:29 AM PDT ) Permalink

Wednesday January 23, 2008
Improved Callstack information in JavaScript
In this post I blogged about a simple function to get the call stack in JavaScript. Here is an improved variant of the same function: /** * This function returns an array of objects that contain the information about call stack. */ function callstack() { function StackFrame(funcName, funcSource, flName, lnNumber) { this.functionName = funcName; this.functionSource = funcSource; this.fileName = flName; this.lineNumber = lnNumber; } StackFrame.prototype.toString = function() { return 'at ' + this.functionName + '(' + this.fileName + ':' + this.lineNumber + ')' ; }; StackFrame.prototype.toHtml = function() { return '<table border="0">' + '<tr valign="top"><td><b>Name: </b></td><td>' + this.functionName + '</td></tr>' + '<tr valign="top"><td><b>File: </b></td><td>' + this.fileName + '</td></tr>' + '<tr valign="top"><td><b>Line: </b></td><td>' + this.lineNumber + '</td></tr>' + '<tr valign="top"><td><b>Source:</b></td><td>' + ( this.functionSource ? '<pre>' + this.functionSource.toString().replace(/\</g, '<').replace(/\>/g, '>') + '</pre>' : 'unavailable') + '</td></tr>' + '</table>' ;
}; var stackFrameStrings = new Error().stack.split('\n'); // remove first two stack frames stackFrameStrings.splice(0,2); var stackFrames = []; for (var i in stackFrameStrings) { // a stack frame string split into parts var stackFrame = stackFrameStrings[i].split('@'); if (stackFrame && stackFrame.length == 2) { stackFrames.push( // Stackframe object new StackFrame(stackFrame[0], eval(stackFrame[0].replace(callstack.sansParenthesisRE,'')), stackFrame[1].match(callstack.fileNameLineNumberRE)[1], // first group stackFrame[1].match(callstack.fileNameLineNumberRE)[2] // second group ) ); } } return stackFrames; } callstack.sansParenthesisRE = /[(][^)]*[)]/; callstack.fileNameLineNumberRE = /(.*):(\d+)$/;
Here is how it canbe used. The callstack function code above is assumed to be stored in a file named Utilities.js .
<html> <head> <title>Callstack</title> <script src='Utilities.js'></script> <script> function called() { var cs = callstack(); document.write(cs[0].toHtml()); document.write(cs[1].toHtml()); document.write(cs[2].toHtml()); } function caller() { called(); } </script> </head> <body onload="caller();"> </body> </html>
Here is the output as displayed in the browser (FireFox): | Name: | called() | | File: | file:///languages/javascript/Callstack.html | | Line: | 7 | | Source: | function called() { var cs = callstack(); document.write(cs[0].toHtml()); document.write(cs[1].toHtml()); document.write(cs[2].toHtml()); } |
| Name: | caller() | | File: | file:///languages/javascript/Callstack.html | | Line: | 13 | | Source: | function caller() { called(); } |
| Name: | onload([object Event]) | | File: | file:///languages/javascript/Callstack.html | | Line: | 1 | | Source: | function onload(event) { caller(); } |
Posted by sandipchitale
( Jan 23 2008, 07:46:59 AM PST ) Permalink
|