Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Saturday, December 4, 2010

Why I will Never Use Spring Tag Libraries in my HTML

The Facts - Web Design and Web Development Involve Completely Different Skills


I work with a team of developers and a team of designers. The designers I work with know Photoshop like they know the back of their hand. They are experts in writing clean, standards based, cross browser compatible HTML and CSS. They design and produce high-quality, beautiful, $15k websites for our clients. Their code validates with W3C validators. The results are amazing.

Our web developers know Java. They can pound away at any server-side problem and produce a solution. They use Struts, Spring, Restlets, JSP, JSTL, Velocity, they can configure Jetty and Tomcat, and they can look at log files and solve problems.

However, if you give them an HTML document, they'll give it such a severe beating that it becomes unrecognizable by it's original creators.

The beautiful HTML turns into a 3 headed monster with unclosed tags, numerous validation errors, and no IE support. The developers struggle for days with guesswork of adding a tag here, removing a tag there, editing a CSS rule here, and who knows what else there.

Of course, the designers are unable to help because of the code soup that results from mixing JavaScript, Java, and HTML into a JSP page.

The resulting web application looks great on the outside, but under the hood it's an absolute nightmare! Ask the designers to go back in and make a design update, and their faces go blank. A 4 hour change takes weeks! The developers can't make the changes because they barely got the HTML integrated with the backend system.

So developers and designers sit side by side trying to understand all of the complexity. The designers can't determine what the application is doing with the HTML, and the developer can't understand what modifications to make to the HTML. Logic mixed in with the HTML is of course overwhelming and makes the code completely unmaintainable.

In summary, designers and developers just plain have different skill sets, at least at my company, and it's foolish of us to think that designers and developers can use the same tools. People do better at what they specialize in, and to try to force that change is wasted energy.

How do I know this, you ask? Because I've fought this fight for years and have continued to lose miserably. "Eclipse is a software development tool, not a design tool", they tell me, "and we're not using it". End of discussion.

Of course, I have convinced a designer or two to try it out. In the end it just slowed both them and me down because Eclipse would inevitably break, and I would end up having to help fix it. Afterwards, we both silently agreed it was a bad idea. The designer stopped using it, and I stopped asking questions.


Light at the end of the tunnel - Keep Content and Behavior Separate



Recently, I took on the project of testing out a new Google App Engine feature and put together a prototype of Google's new ChannelAPI using Google App Engine SDK 1.4.0. Since we have chat designs, I used this as an opportunity to experiment with some new ideas regarding HTML integration with a J2EE application. Below are the details:

  • The HTML exists as a static HTML page. My rule for this experiment is no JSP pages!

  • I use JQuery to bind all my click event handlers dynamically, which leaves my HTML free of pockmarks and other markup that would bind it to the framework.

  • Chat applications involve inserting data in a message window. I used the concepts of manual templating to inject the messages dynamically, without mixing HTML and JavaScript. I'll describe more on this below.

  • My application sends messages to the server using AJAX. Calls to the server are made through the bound click event handlers. No tag libraries! Only client-side code!



I've observed designers over the years, and I've also observed developers. Our designers put placeholders in the HTML they create to mark where the dynamic content would go. The pages can be loaded as static files, and look just like the final result except the fake data. Below is an example of the body of an HTML file, with the placeholder in bold:

<body>
   <input type="text" name="alias" value="James" />
   <button id="join" value="Join Room!">Join room!</button>
   <button id="leave" value="Leave Room!">Leave room!</button>
   <button id="test" value="Test Message receive!">Receive Test Msg!</button>
   <div id="messages">
      <div class="message">
          <div>
              <span class="name"></span>
              <span class="timestamp"></span>
          </div>
          <div class="text"></div>
      </div>

   </div>
   <textarea id="messageBox"></textarea>
   <button id="sendBtn" value="Send">Send</button>
</body>

Now, my development team would normally be tempted to solve this problem by pulling out the bold HTML and placing it in the JavaScript callback method as follows:

// create the div for the message
var message = "<div class='message'><div><span class='name'>"+name+"</span><span class='timestamp'>"+timestamp+"</span></div><div class='text'>"+message+"</div></div>";

// inject the div onto the page
document.getElementById("messages").innerHTML += message;


When our designer needs to add a new feature to the chat application, he'll have to study the HTML that's inside the JavaScript to figure out where to make the changes. Instead of focusing on his area of expertise, the front-end, he'll have to become an expert on the actual application's inner workings. He'll need to understand Comet, JavaScript, and how the application works. As you can imagine, this is an extremely inefficient use of his time.

A better approach would be to use a templating engine, such as Velocity or Freemarker:

      <div class="message">
          <div>
              <span class="name">${NAME}</span>
              <span class="timestamp">${TIMESTAMP}</span>
          </div>
          <div class="text">${MESSAGE}</div>
      </div>

This is better, but it's still based on old ideas that still suffer from the same problems. I can't give a JSP file to a designer who knows nothing about Spring, Tomcat, Jetty, Eclipse, JavaBeans, and other technologies that bind the document to the framework. In addition, even if he did understand these technologies, he doesn't have 4 hours to spare to setup his development environment for just a 2 hour change. Even with templating, the files can't really be loaded outside of the JVM and outside the context of the framework.

Velocity and Freemarker are marketing ideas that in practice are failures. Anything that involves a developer mixing non-HTML markup with HTML will create more problems than it solves.

Instead, I took the approach of leaving the fake, empty HTML-valid message in the HTML and using it as the actual template:

var template;
$(document).ready( function() {
chat_template_read_only = $('.message'); // store the original template from the HTML (in bold) for later use.
};

Now, in my callback method, I do the following:

// make a copy from the template I saved earlier
var message = chat_template_read_only.clone();

// now use JQuery DOM methods to inject the content in the appropriate places in the copy.
message.find('.name').html(name);
message.find('.timestamp').html(timestamp);
message.find('.text').html(text);

// dynamically inject the new message into the HTML.
$('#messages').append(message);


Here you can see I'm accomplishing the same goal. I'm placing the dynamic content in an HTML block and injecting it into the DOM. Now, if in 6 months the design team needs to add a department header and maybe a response time to each chat, we can give them the current, live, HTML file and they can load it outside the context of the web framework, code their changes, and then send it back to the development team.

We can integrate new changes simply by making changes to the Jquery CSS selectors in the JavaScript files! There is no need for the web designers to understand anything about Eclipse, Java, Jetty, Tomcat, how to configure the application, or any of the applications inner workings.

Let me repeat that one more time: The HTML document is not bound to the framework and can be loaded outside the framework. It can be loaded from an Apache server, it can be loaded from the desktop by clicking on the file. It can be modified by the designers without needing to look at any Java, JSP, or JavaScript.


Spring Taglibraries



I was looking at Spring's JSTL tag, which is used to bind server-side data to an HTML form element so the form can be rendered with a session ID and any preloaded data from the server. The server-side tag generates an HTML form tag.

The benefit here is that web designers are supposed to be able to work with these tags, or at least that's what they say. In practice, in all my years of software development and programming, I have yet to ever see this magical unicorn walk out of the shadows and into the sunlight.

Where are these mystical organizations that operate in this manner? I'd like to meet one of these developers. Are they human? Do they eat and breathe like I do or are they just mere fiction?

This tag is useful in cases where a developer needs to pre-load the form with data from a persistent object. Although I'd love to just ask the developers not to use it anymore, but that's just as difficult as trying to set the web designers up with Eclipse! It just ain't gonna happen!

The problem with these templating languages and tag libraries is that they completely alienate the web designers while simultaneously encouraging the developers to trash the HTML. These frameworks make it impossible for designers to use their own tools. Although these templating engines claim their goal is to allow everyone to work together, they fall way short of the mark. These frameworks were obviously developed by programmers who have absolutely no clue about design.


JQuery Manual Templating



While looking at a <form:form> tag, I thought to myself: "Now wouldn't it be nice if I could use some tool on the server-side to bind my data to that form dynamically, without having to actually make any changes whatsoever to the actual HTML document, just like I did on the client side with JQuery?

Then it hit me! Java doesn't have anything like this that I know of, but since JQuery can run in server-side JavaScript, perhaps Rhino or Claypool is the answer! Imagine using JQuery to manipulate HTML documents on the server side without ever having to modify or template the code.

What I picture is a form of binding server-side tags dynamically. If we can use CSS selectors on the client side, why not create a method of doing so on the server side. I picture a solution such as this:

Import server-side JQuery into our JSP page:

<script type="extjs" src="server-side.js"><script>

// server-side.js
$('form').replace('form:form');
$('input').replace('form:input');


Now, instead of editing the HTML directly, we can bind our server side tags dynamically. When the designer needs to update the page, he can load it completely independent of the Spring environment, make modifications to it, and give the file back to the developer.

There is currently no solution out there for this, but I would greatly appreciate any advice from anyone who has ideas/suggestions for how to get this concept started!

Saturday, June 13, 2009

Revolutionary Testing Tools for AJAX Applications

Revolutionary Testing Tools for AJAX Applications

http://blog.browsermob.com/2008/12/faq-how-do-you-compare-to-selenium/

A few years ago, we used JMeter to try and load test a chat application we were building. Since the chat application used Comet and AJAX, I knew that the JMeter test was going to be grossly inaccurate. However, we did the best we could with tools that clearly weren't right for the job, as nothing was out there that could simulate an AJAX or Comet load test.

A few weeks ago, while working with some other consultants on a project, we discussed the use of Selenium to run some functional testing on a Firefox Extension that inserts signatures into an email. We needed a tool that could automatically send an email using Gmail, Yahoo, and Hotmail, and verify that the signature was still injecting. From my days writing HTML Reply Signatures for Gmail, I knew that this was indeed important, as any change by these third parties could have a drastic effect on the tool's ability to insert a signature.

Today, one consultant and I worked to try to insert an email address into the "To" field of the Gmail Compose window using Selenium. I've done this already in the Firefox extension, and anyone who has ever written a Greasemonkey script or Firefox extension that works with Gmail 2 can attest that this is not always an easy task if you are working outside of the API exposed by Gmail. Google engineers have put lots of effort in writing server-side code that ensures that all the id attributes in the Gmail application randomly change each session. Their creativity has sparked our creativity, and we have solved this problem. With enough time and patience, any problem can be solved.

Anyway, with Selenium, one must locate elements in the HTML of a web application by using XPATH queries. Armed with my trusty Firebug tool, I inspected the element in question and worked my way up the tree one element at a time, writing down the element tag names and positions at each step. Like a complex code, we ended up with long XPATH queries, a seemingly endless series of div[1]/div[2]/div[1]/div[1]. Although I would have preferred to just use JavaScript and a good for loop or regular expression to locate what I wanted, being a code cracker and approaching this problem from another angle was an eye-opener, XPATH is perhaps the way to go!

So that's a little background on my experience so far with testing tools. Selenium isn't a load testing tool of course, but it's a great tool to automate functional testing. It's almost like a macro recorder, similar to iMacros. Our plan is to set our test up on a VMWare image and configure this to run automatically every day. We'll get emails with our signature if it's successful, and broken or no email if it's not successful. We're also configuring it to be really loud and obnoxious if it does detect that something is amiss, just so we don't gloss over the automated emails.

Selenium can do functional testing, but what about load testing? Sure, Selenium can do load testing as well! Selenium uses real web browsers in testing, but it's up to the person doing the tests to go out and purchase the hardware to run the tests. In other words, if you want to do a 100 user load test with Selenium, you need to have 100 computers in your lab and 100 people to all click "Run" at the same time.

This is analogous to a symphony with you as the conductor who tells everyone exactly when to click "Run Test".

Of course, coordinating such an event can be costly, so one of the developers of Selenium Remote Control founded BrowserMob. BrowserMob solves this issue by providing the hardware. They claim to load test your web application using Selenium scripts and N number of real web browsers! I would be really interested to know how this was accomplished and how the costs have been kept so low.

To start, they probably use VMWare and Linux, which is one way to reduce the amount of physical hardware while still trying to simulate real hardware. They say they use Firefox 3.0, which is available on Linux. Finally, if Selenium Remote Control launches Firefox browsers to simulate functional tests, then my guess is BrowserMob is controlling a series of Selenium Remote Control instances, all running on VMWare Linux machines, and allowing BrowserMob to monitor the load.

While there are some costs associated with BrowserMob, I imagine one could use Selenium Remote Control installed on several VMWare images to run a small load test. If anyone has experience with either Selenium Remote Control or BrowserMob, I'd love to hear your thoughts on the two products!

Monday, July 21, 2008

JavaScript and Java are Pass By Value

Proof that JavaScript and Java are Pass By Value



Pass by value and pass by reference can be daunting at times, and I too have been confused and frustrated at all of the babbling about whether or not Java is one or the other, that is, until I saw an article featuring the Litmus test. I've seen the Litmus test in college, but it didn't make sense completely until reading Scott Stanchfield's "Dammit" article.

Today I was reading Jeff Cogswell's article asserting that JavaScript is pass by value. The blog author is indeed correct in his assertions; however, there were many comments rebutting his arguments. I thought it would be best to support his arguments by applying the Litmus test to JavaScript to prove once and for all whether or not JavaScript is pass by value or pass by reference.

Java is clearly pass by value. Scott Stanchfield's statement says it best: "Objects are not passed by reference. A correct statement would be Object references are passed by value."


The JavaScript Litmus Test



I decided to apply the Litmus test to JavaScript and see what the results are. Here is what I have so far:


function doLitmusTest() {
     var a1 = 5;
     var a2 = 7;
     swap(a1,a2);
     alert(a1 + ","+a2);
}

function swap(a,b) {
    var temp = a;
    a = b;
    b = temp;
}

window.addEventListener("load",function() { doLitmusTest(); },true);



The output is as follows:

5,7

The values were not swapped. JavaScript fails the Litmus test, as Java did. This means that JavaScript is also pass by value.

In Java, there is a workaround to being able to implement the swap function, and it also works in JavaScript:


function anotherTest() {
     var obj1 = { value: 5 }; // JSON notation
     var obj2 = { value: 7 }; // JSON notation
     swapValue(obj1,obj2);
     alert(obj1.value + "," + obj2.value);
}

function swapValue(objA,objB) {
     var temp = objA.value;
     objA.value = objB.value;
     objB.value = temp;
}

window.addEventListener("load",function() { anotherTest(); },true);



The output is:
7,5

In Java, data can be "wrapped" in an object to allow the value to be changed. JavaScript behaves in the same manner. All values, both primitives and object references are passed by value. With primitives, changes we make to one copy of a variable do not affect changes to another copy.

The rule is the same with Object references. Objects are not passed in as parameters in Java or JavaScript, object references are passed as parameters. References point to a specific location in memory. Three references can all point to the same location, so if the data located at that spot in memory is changed, the change will be reflected for all of the references that point to that spot.

However, changes to the reference itself are not reflected. A rule of thumb to remember is that when implementing the swap method, you can only change data by calling setter and getter methods, or by accessing public properties. However, making changes to the object reference instruct the object reference to point to a different location. This is why swapValue worked as expected while swap did not.

Below is a sequence of "visual art" to demonstrate the concepts visually:


new operator uses new memory space

Object A and Object B are instantiated and new memory is allocated on the heap.



using new on object A creates new space in memory

Object A is assigned a reference to new memory space because the "new" keyword was used.



using setter changes value in memory location

The value of the object referenced by B is changed to a new value, but the object reference still points to the same location in memory.

For A, the "new" operator created new space in memory and instantiates a new object. The "12" is located in a different spot in memory.

B, on the other hand, has a value that was set using a setter method. Thus, the value has changed from "7" to "2" without destroying the original object.



multiple objects reference the same memory space
Objects A, C, and D all point to the same place in memory. If a setter method is called on one of the object references, the value is changed in all 3 object references because they all point to the same location in memory.

A good analogy to use to explain this concept is "nicknames". For instance, my name is James, but people also refer to me by Jim. Additionally, I've been called "Mort" before as well. All three names point to the same object, me! In the example I've shown you, A, C, and D are all names of the same object.

Friday, June 27, 2008

HTML Multiple Reply Signatures for Gmail 1.0.2.3

Don't get too excited. The Multiple HTML Reply Signatures Extension 1.0.2.3 update doesn't include too many new features. I got rid of the red update link that appears in the toolbar. I don't think it was working correctly. In addition, it took up valuable browser real estate. Bad idea.

I did try to see what would happen in Firefox 3. Sadly, the Firefox Extension doesn't work in Mozilla's newest and fastest browser. The problem isn't the editor or even the signature injection. It's the module that reads data from the XML file. This was a hack anyway. I could probably get by with using the Firefox RDF API or perhaps store the signatures using the preferences system.

The good news is, converting to Firefox 3 wouldn't be hard. The bad news is that I don't have time to do it. We just need to fix the mechanism that reads signatures from the XML data file! That's it! Everything else appeared to work when I tested it!

Anyone know any JavaScript who is bored? HTML Multiple Reply Signatures for Gmail is licensed under the GPL! You can crack open the XPI and try to fix this yourself! I'll even tell you what files to modify if you email me!

I did start working on a version for Gmail 2. Interestingly enough, there aren't many solutions out there for Gmail 2, yet there was tons of competition for Gmail 1. I have a prototype that Susan Hemmersmeier has happily tested for me. It's very buggy though. Too buggy to put up on the blog, and too buggy for her to use.

Susan asked me when this will be finished. I hate to keep promising that "I'll eventually get to it.". You see, thanks to this blog, I landed some contract work! It's a lot of fun, but it takes up a lot of time. As a result, it would appear that HTML Multiple Reply Signatures for Gmail may be a (sniff...) dying project...

Do you have the skills to resurrect it from it's ashes? Let me know! I can definitely provide the moral support and answer technical questions, I just can't devote programming time to it at the moment.


James

Tuesday, June 10, 2008

getElementByAttribute

I don't use many JavaScript libraries, I prefer to write my own implementations of code that I need so that I don't have to import the entire library (although the example I am referring to in this post was not written by me). With Java, the compiler weeds out things you don't use, but the browser doesn't. There is really no mainstream mechanism for the browser to say "Only import method X".

I've used Taconite and DWR for a current project, but as a general rule I've found that for what I do, most libraries are limited to just solving one part of the problem. Taconite is great for AJAX support and being able to add XHTML to the DOM while still maintaining a readable XHTML file so you don't have to wrap everything in DOM methods. However, it doesn't cut it with cross-domain issues. Similarly, DWR is great for making AJAX calls by invoking a JavaScript wrapper with the same name as your Java class method, but it suffers from the same limitation.

I'll write more on this topic later, but the main purpose of this post is to identify the source of some code I found on Mahesh Lambe's blog

Mahesh obviously paid attention in school! The getElementByAttribute function that he wrote uses two inner functions and recursion to search for an element that contains the attribute you specify and the value you specify. The search consist of making a recursive call by diving down through all of the child elements in one call while checking the sibling in another call. This results in a thorough check down the DOM tree. It reminds me vaguely of something I may have done in Lisp with Fibonacci numbers in college.

This is one of the reasons that I love JavaScript. I just don't come across code like this in Java. With JavaScript, the code seems more true to the spirit of Computer Science, while still representing the language of interactive web applications.

Saturday, May 10, 2008

Open Source JavaScript Compressor

Are you concerned about having your Firefox Extension JavaScript code compromised? XPI files can be extracted and code can be easily viewed. One solution that works very well for many organizations that wish to keep their JavaScript code secret is to use a JavaScript obfuscator.

Also known as a script compiler or script compressor, an obfuscator takes human-readable JavaScript code and converts it into text that is virtually impossible for humans to process. When you're ready to deploy your product live, your developers can "obfuscate" a version of the code for distribution and maintain the original human-readable version for continued maintenance and development.

In addition to making it difficult to reverse-engineer, compressed JavaScript files are generally 40% to 60% smaller than their aesthetically pleasing human-readable counterparts, as a result of comment, whitespace, and line break removal.

http://www.javascript-source.com/

Please see the above link for a quick example of the difference between a human-readable JavaScript function and an obfucscated function. I wouldn't recommend purchasing this version though as there are open source versions out there that will accomplish the same goal.

http://javascriptcompressor.com/

This version is Dean Edward's Packer. The problem with this is that the website has a decoder. This kind of defeats the purpose of obfuscation, and I would recommend it only for compression and not obfuscation.

These tools appear to be a great way to keep proprietary JavaScript code from falling into the wrong hands. Obfuscation is not prefect or foolproof, but consider this question: Is a thief more likely to snoop around in a car with unlocked doors or one that is securely locked?

Here are some links to free or open source obfuscators. All three work from the command line:

- YUI Compressor
- ObfuscateJS JavaScript Obfuscator
- JSO (JavaScript Obfuscator)

Thursday, October 11, 2007

Nested-Nested Quotes

Larry Wakeman of Memory Pharmaceuticals recently sent me a reminder about a follow-up article that I forgot to write. Back in April, I addressed the concept of quotes within quotes within quotes and how to handle this phenomenon.

Any programmer who has ever had to write Greasemonkey scripts, as well as to perform any type of server-side or client-side programming has or will encounter this particular problem. For example, a JavaScript function that generates HTML that contains attributes that refer to JavaScript functions that take strings as parameters, will require some cleverness on the part of the developer, especially if the parameter passed into the JavaScript function is determined at the time the HTML is generated:


<html>
     <head>
     </head>
     <body>
         <script type="text/javascript">

    function alertParameter(stringParameter) {
         alert(stringParameter);
    }

    var topLevel = "test";

    function generateHTML(topLevel) {
         document.write("<a href=\"#\" onclick=\"alertParameter('"+topLevel+"')\">Click this link to see the result</a>");
    }

    generateHTML(topLevel);
        </script>

    </body>
</html>



Here is a breakdown of the above process: The text "document.write" is what I refer to as top level. This is the actual command that outputs the string of text included within the outer quotes. The outer quotes are the quotes that wrap the text inside the parenthesis of the document.write method.


document.write(" /* These quotes are the outer quotes */ ");


Note that there are two types of quotes: Single quotes and double quotes. We can use either to represent the outer quotes. For this example, I chose double quotes. The first set of inner quotes, like the outer quotes, can also be double or single quotes. However, if the inner quote is the same as the outer quote, then the inner quote must be escaped. Consider the following example:

Nested JavaScript Quotes Example 1



document.write("<div onclick=\"alert('ht')\">click me</div>");


The above example is the same as the following example:

Nested JavaScript Quotes Example 2



document.write("<div onclick='alert(\"ht\")'>click me</div>");


Also, to demonstrate that we can use single-quotes as the outer quotes, check out this example:

Nested JavaScript Quotes Example 3



document.write('<div onclick="alert(\'ht\')">click me<div>');


Take a careful look at the above three JavaScript nested quote examples. Understanding this concept is a prerequisite to understanding deeper JavaScript nested quotes.

As I mentioned, the outer quote can be either a double or single quote, and the first inner quote can be either a double or a single quote independent of the choice made for the outer quote. In Example 1, I used double quotes for both the outer and inner quote, whereas in Examples 2 and 3 I alternated between single and double quotes. For convenience, here is Example 1 again:

Nested JavaScript Quotes Example 1



document.write("<div onclick=\"alert('ht')\">click me</div>");


It may seem confusing at first as to how this is possible, until you see the output in the browser source (of the generated HTML, that is. I'll go into more detail on this later):


<div onclick="alert('hi')">click me</div>


The outer quotes don't appear in the generated HTML. Those were top level quotes. They served only to wrap what was being generated. As you can see, the escaped double-quotes render as actual quotes, and cause absolutely no conflict.

Nested JavaScript Quotes Example 4



document.write('<div onclick="alert(\'ht\')">click me</div>');


Example 4 produces the same output! Except in example 4 it is the single quotes that must be escaped, as this time single quotes represent the outer quotes.


JavaScript Inner, inner quotes



By this point, it should be quite apparent that there are several combinations of outer and inner quotes that can be combined without causing a non-terminated string literal error. However, after choosing an outer and an inner quote, choices become much more limited. Instead, from this point forward, nested quotes must alternate between single and double quotes. Below is an example:


<html>
     <head>
     </head>
     <body>
         <script type="text/javascript">

    function alertParameter(stringParameter) {
         alert(stringParameter);
    }

    var topLevel = "test";

    function generateHTML(topLevel) {
         document.write("<a href=\"#\" onclick=\"alertParameter('Say \\'Hello World\\'')\">Click this link to see the result</a>");
    }

    generateHTML(topLevel);
    </script>

    </body>
</html>


You may have noticed that the previous paragraph contains a sentence with strikethrough styling. After trying the example I was going to try, I realized that the rule that the quotes must alternate is not necessarily true. I'll explain, but first, here is the output when clicking the link:

Say 'Hello World'

Definition of literal quote: This is a quote that represents a quote as text in a string. A quote that marks the beginning or end of a string is a non-literal quote, and it is not part of the actual text. A non-literal quote can be represented as a literal quote by escaping it with a backslash (\) character.

Since the outer quote is a double quote, the inner quotes are literal quotes in the string. If the outer quotes were single quotes, then double quotes would be literal. As a result, I can place as may single quotes in a row as I want without affecting the String. However, this will affect not what occurs with the output, but what occurs with the output of the output:

(" ... onclick=\"alertParameter('Say \\'Hello World\\'')\"> ... ")

Outer quote = " (This marks the beginning and end of the string)
Inner quote = \" (Escaped as to not flag "beginning/end of string")
Third-tier quote = ' (Literal quote)
Fourth-tier quote = \\' (Literal quote that will be generated as an escaped outer quote)

This is what really makes this JavaScript nesting quote process complicated. As I mentioned, the single quote is a literal quote. This means the string treats it as a normal character. However, in the HTML -- in the output that is -- the single quote becomes an outer quote. The single quotes around 'Hello World' are literal quotes in the JavaScript code, but in the HTML, these single quotes are inner quotes that must be escaped. However, using a single \' would simply result in a '. So the trick is to escape the slash. Thus, a document.write("\\'"); would produce a \' in the HTML, and this would be resolved to a ' if processed again.

Essentially, you must take two things into consideration when dealing with escaping a quote in JavaScript. If it needs to be escaped in the inner string, then you must think one level deep. It helps to move backwards. Write your desired output first, and then go through and "wrap it" with the tools that would generate it:


<script type="text/javascript">document.write("<a href=\"#\" onclick=\"alert('Say \\'Hello World\\'');\">click here</a>");</script>


I want to dynamically generate this embedded JavaScript from the server with PHP. So I'll first verify that this works in between the body HTML tags of a PHP document. It does indeed work. Next, I'll wrap it with a PHP echo statement:


<? echo "<script type=\"text/javascript\">document.write(\"<a href=\\\"#\\\" onclick=\\\"alert('Say \\\\'Hello World\\\\'');\\\">click here</a> \");</script>'"; ?>


Escaping JavaScript quotes is recursive. After wrapping the PHP echo around the JavaScript with double quotes as outer quotes, I then had to escape the previous outer quotes. I then had to escape the inner-inner double quotes not once, but twice. Once to escape the backslash used to escape the quote, and once to escape the quote so that PHP wouldn't treat it as the end of the string. What I found most interesting is that the single quote used as the outer wrapper of the alert text was ignored during the PHP wrapping process because it is a literal quote. However, the innermost single quote had to have two backslashes added -- once to add another backslash and once to escape that backslash! Each time a wrapper is added, an escaped special character must be escaped again because during each iteration, a backslash escapes a backslash!

In summary, I'm not sure if this little exercise will be of any practical use. Perhaps it would be a good problem solving exercise during an employment interview to see how good a programmer is at dealing with complex layers of abstraction. Perhaps a situation will arise where one actually needs to generate different JavaScript functions based on different criteria. I can't think of any examples other than the Multiple HTML Reply Signatures Embedder for Gmail Greasemonkey script that I wrote, and sometimes I think that there may have been an easier way to generate a dynamic-drop down list in Gmail without having to nest quotes in JavaScript. Bottom line -- I'm not sure. However, if this has proved helpful, please share your story with me!
Google