<?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>Danny Thorpe &#187; JavaScript</title>
	<atom:link href="http://dannythorpe.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://dannythorpe.com</link>
	<description>Dream &#38; Deliver</description>
	<lastBuildDate>Tue, 07 Feb 2012 17:50:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Calculating Browser Client Height</title>
		<link>http://dannythorpe.com/2009/10/02/calculating-browser-client-height/</link>
		<comments>http://dannythorpe.com/2009/10/02/calculating-browser-client-height/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 22:14:04 +0000</pubDate>
		<dc:creator>Danny Thorpe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[web app]]></category>

		<guid isPermaLink="false">http://dannythorpe.com/2009/10/02/calculating-browser-client-height/</guid>
		<description><![CDATA[When you&#8217;re writing a rich Internet application (RIA) in HTML and JavaScript, sometimes you need to programatically place a DOM element relative to the right or bottom edge of the visible browser window. For example, if you want to popup a help balloon near an item of interest, you probably want to make sure that <a href='http://dannythorpe.com/2009/10/02/calculating-browser-client-height/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re writing a rich Internet application (RIA) in HTML and JavaScript, sometimes you need to programatically place a DOM element relative to the right or bottom edge of the visible browser window. For example, if you want to popup a help balloon near an item of interest, you probably want to make sure that the balloon is fully visible on the screen &#8211; not hanging off the edge of the screen, partially obscured.  I haven&#8217;t found a CSS way to accomplish that, but here are some tidbits I have found:</p>
<p>A quick web search on calculating browser window height reveals that different browsers have different ways to find the browser&#8217;s window client height.  In Netscape / Mozilla browsers, you can use window.innerHeight.  For IE, some sources suggest using document.body.offsetHeight, but I&#8217;ve found this falls short when the HTML content does not completely fill the browser window.  document.documentElement.clientHeight returns the actual window client height in IE.</p>
<p>The jQuery JavaScript library has some handy functions for calculating an element&#8217;s pixel location and pixel width and height, with or without consideration for borders, padding and margin.  $(&#8220;.myclass&#8221;).outerHeight() will give you the pixel height of the first element with a CSS class of &#8220;myclass&#8221;, including borders and margins.</p>
<p>$(&#8220;body&#8221;).outerHeight() returns the same value as document.body.offsetHeight, which will be less than the window height in a short HTML document and could be much larger than client height in a scrolling window.</p>
<div style="text-align:center;width:100%;"><div style="margin:0px 0px 0px 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-0861479594738165";
/* End of Post */
google_ad_slot = "6510912161";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></div><p><a class="a2a_button_twitter_tweet addtoany_special_service" data-count="none" data-url="http://dannythorpe.com/2009/10/02/calculating-browser-client-height/" data-text="Calculating Browser Client Height"></a><a class="a2a_button_google_plusone addtoany_special_service" data-annotation="none" data-href="http://dannythorpe.com/2009/10/02/calculating-browser-client-height/"></a><a class="a2a_button_facebook_like addtoany_special_service" data-href="http://dannythorpe.com/2009/10/02/calculating-browser-client-height/"></a><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fdannythorpe.com%2F2009%2F10%2F02%2Fcalculating-browser-client-height%2F&amp;title=Calculating%20Browser%20Client%20Height" id="wpa2a_4">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://dannythorpe.com/2009/10/02/calculating-browser-client-height/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recent Google Homepage / GMail Widget Update Laced With Script Errors</title>
		<link>http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/</link>
		<comments>http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 19:47:24 +0000</pubDate>
		<dc:creator>Danny Thorpe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[code quality]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[GMail]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[IE]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[script errors]]></category>

		<guid isPermaLink="false">http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/</guid>
		<description><![CDATA[About two days ago, my Google homepage suddenly became hostile toward me.  By hostile, I mean my IE7 browser is suddenly reporting a bunch of JavaScript errors and faults when loading the Google homepage that it wasn&#8217;t reporting before.  Whenever I visit my Google homepage now, I have to wade through 5 or 6 JavaScript error <a href='http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>About two days ago, my Google homepage suddenly became hostile toward me.  By hostile, I mean my IE7 browser is suddenly reporting a bunch of JavaScript errors and faults when loading the Google homepage that it wasn&#8217;t reporting before. </p>
<p>Whenever I visit my Google homepage now, I have to wade through 5 or 6 JavaScript error notifications before I can do anything.  I suspect the culprit is the Gmail gadget for the Google homepage, as I continue to get script errors while trying to browse email in-situ on the homepage.  The gmail gadget is also missing scrollbars on long messages. None of these problems are present when using Gmail itself, just when using the Google homepage.</p>
<p>As a developer, I have to have script debugging enabled in my browser.  This enables me to debug my web app code in the browser, but it also has the unfortunate side effect of pointing out JavaScript errors on every site I visit.  It&#8217;s surprising how much crappy code is out there in production.  Slashdot has degraded into the pretty much unusable range in recent months, and now the Google homepage / Gmail widget is following suit.</p>
<p>The script errors are not specific to IE.  Firefox 3 also notes 5 critical errors in its error console when navigating to my Google homepage. To Firefox&#8217;s credit, recording these script errors in a log rather than with popup dialogs is much less intrusive than IE, but that also means that significant script errors can go unnoticed by developers testing their web apps with Firefox.</p>
<p>The errors are:</p>
<p>Error: _IG_AddCustomEventHandler is not a function<br />
Source File: http://www.google.com/ig/f/lZ_kPjC_O4s/lib/libcore.js<br />
Line: 43</p>
<p>Error: _IG_AddEventHandler is not a function<br />
Source File: http://www.google.com/ig/f/irJtX0bmDdM/lib/libdynamic-height.js<br />
Line: 4</p>
<p>Error: _IG_Json is undefined<br />
Source File: http://www.google.com/ig/f/_pVqt4t_Qx8/lib/libviews.js<br />
Line: 1</p>
<p>Error: _IG_Prefs._parseURL is not a function<br />
Source File: http://www.google.com/ig/f/lZ_kPjC_O4s/lib/libcore.js<br />
Line: 78</p>
<p>Error: _IFPC is undefined<br />
Source File: http://www.google.com/ig/f/irJtX0bmDdM/lib/libdynamic-height.js<br />
Line: 2</p>
<p>So, to whoever turned on the new code a few days ago for either the Google Homepage or the Gmail widget for the homepage:  Please review your code and fix the crappy script that you&#8217;re dumping on us.  Your developer bretheren thank you for a speedy resolution so that we may get back to debugging our apps instead of debugging yours.</p>
<p><a class="a2a_button_twitter_tweet addtoany_special_service" data-count="none" data-url="http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/" data-text="Recent Google Homepage / GMail Widget Update Laced With Script Errors"></a><a class="a2a_button_google_plusone addtoany_special_service" data-annotation="none" data-href="http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/"></a><a class="a2a_button_facebook_like addtoany_special_service" data-href="http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/"></a><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fdannythorpe.com%2F2008%2F12%2F18%2Frecent-google-homepage-gmail-widget-update-laced-with-script-errors%2F&amp;title=Recent%20Google%20Homepage%20%2F%20GMail%20Widget%20Update%20Laced%20With%20Script%20Errors" id="wpa2a_8">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://dannythorpe.com/2008/12/18/recent-google-homepage-gmail-widget-update-laced-with-script-errors/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Cross-Domain Transport with Window.Name</title>
		<link>http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/</link>
		<comments>http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/#comments</comments>
		<pubDate>Mon, 28 Jul 2008 21:46:44 +0000</pubDate>
		<dc:creator>Danny Thorpe</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[window.name]]></category>
		<category><![CDATA[XDR]]></category>

		<guid isPermaLink="false">http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/</guid>
		<description><![CDATA[In the fall of 2006 I was wrestling with VS debugging JavaScript in IE and Venkman in Firefox teasing out problems and holes in the cross-domain channel library we were building for Windows Live and the Windows Live Contacts Control. One of the most aggrevating aspects of debugging cross-domain JavaScript is that JavaScript debuggers do not provide the same <a href='http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>In the fall of 2006 I was wrestling with VS debugging JavaScript in IE and <a href="http://www.mozilla.org/projects/venkman/">Venkman</a> in Firefox teasing out problems and holes in the <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">cross-domain channel library</a> we were building for <a href="http://www.live.com">Windows Live</a> and the <a href="http://dev.live.com/contacts/">Windows Live Contacts Control</a>.</p>
<p>One of the most aggrevating aspects of debugging cross-domain JavaScript is that JavaScript debuggers do not provide the same degree of omniscience we have come to expect from full-featured desktop application debuggers. The reason is that the debugger operates inside the browser, rather than above the browser.  To evaluate an expression, the debugger has to ask the browser&#8217;s JavaScript engine for the element values, or to evaluate the expression itself. Since the debugger is relying on the browser for evaluation, and the browser has access firewalls all over the place to implement same-domain policy restrictions, the debugger can&#8217;t see anything more than what the JavaScript itself can see.  A debugger attached to the execution context of a top level HTML page can&#8217;t see inside the iframes sitting on that page if the iframes are showing pages from a different domain.</p>
<p>This is fixable, but I doubt that it will ever be fixed. I suspect it would be a major restructuring of the browser code to allow a debugger to circumvent the browser&#8217;s security restrictions and see JavaScript state from all domain contexts concurrently. Even just a casual mention of this idea to Mozilla or Microsoft browser teams draws up such fear in their eyes that you change the subject to avoid someone going postal. I can&#8217;t really blame them &#8211; both browser code bases are huge and hairy, and infamous for inflicting great gouts of pain on well-meaning tinkerers who venture too far into the forest. </p>
<p>Besides, it&#8217;s fair to say that the browser teams&#8217; first priority is data security and safety. Omniscient debugger support is understandably lower on their priority list.</p>
<p>At any rate, while I was poking and prodding my cross-domain experiments trying to get a mental picture of how code reality was diverging from the whiteboard spec, I would occasionally notice an odd artifact out of the corner of my evaluator.  Well, this is JavaScript - odd side effects are the norm. On one of these sorties I noticed that the window.name property was preserved across reloads of an iframe.</p>
<p><em>Now that&#8217;s odd.</em></p>
<p>My tinkering took off on a wild tangent.  Passing a lot of data in one string and round-trip would certainly be faster than doing it in multiple smaller round trips required by fragment identifier messaging (FIM).  However, the more I dug into it the more I found that needed to be chased down.  Frustrated and out of time, I pushed a note onto the &#8220;investigate this further&#8221; queue and forced myself back onto the plan of record.</p>
<p>Fast forward to 2008.  <a href="http://www.sitepen.com/blog/2008/07/22/windowname-transport/">Kris Zyp has implemented a cross-domain transport for the Dojo JavaScript library using window.name.</a> Kudos to Zyp for doing the legwork to turn the window.name oddity into a usable data transport pipe <em>and</em> shore up the holes and security vulnerabilities of the raw technique. </p>
<p>I read his post (discovered via <a href="http://ajaxian.com/archives/windowname-meet-dojoxiowindowname">Ajaxian</a>) with skepticism, armed with an array of  &#8221;Yeah, but what about&#8230;&#8221; challenges and security issues I vaguely recall running into in my late night tangent.  Zyp knocked them all down one by one in his detailed writeup.</p>
<p>Well done!</p>
<p><a class="a2a_button_twitter_tweet addtoany_special_service" data-count="none" data-url="http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/" data-text="Cross-Domain Transport with Window.Name"></a><a class="a2a_button_google_plusone addtoany_special_service" data-annotation="none" data-href="http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/"></a><a class="a2a_button_facebook_like addtoany_special_service" data-href="http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/"></a><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fdannythorpe.com%2F2008%2F07%2F28%2Fcross-domain-transport-with-windowname%2F&amp;title=Cross-Domain%20Transport%20with%20Window.Name" id="wpa2a_12">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://dannythorpe.com/2008/07/28/cross-domain-transport-with-windowname/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Cross-Browser Dynamic JavaScript Loading</title>
		<link>http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/</link>
		<comments>http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 18:16:34 +0000</pubDate>
		<dc:creator>Danny Thorpe</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[yahoo]]></category>

		<guid isPermaLink="false">http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/</guid>
		<description><![CDATA[Stoyan Stefanov writes about Non-Blocking JavaScript Downloads on the Yahoo User Interface Blog.  Good content all around, but I&#8217;d like to add a note on an item he somewhat casually skimmed over. In the &#8220;Dependencies&#8221; section of the article, Stefanov describes using the onLoad or onReadyStateChange events of the dynamically generated script tag to receive <a href='http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Stoyan Stefanov writes about <a href="http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/">Non-Blocking JavaScript Downloads</a> on the <a href="http://yuiblog.com/blog/">Yahoo User Interface Blog</a>.  Good content all around, but I&#8217;d like to add a note on an item he somewhat casually skimmed over.</p>
<p>In the &#8220;Dependencies&#8221; section of the article, Stefanov describes using the onLoad or onReadyStateChange events of the dynamically generated script tag to receive notification when that script has been loaded by the browser.  Once you know it&#8217;s loaded, then you know it&#8217;s safe to begin using the code it contains.</p>
<p>This works great for Firefox and IE, but fails completely in the Safari browser.  Safari doesn&#8217;t implement onLoad notifications for script tags.  This forces you to abandon the onLoad technique and instead use the technique of embedding something at the end of each script file to signal when the file has been loaded. </p>
<p>The script libraries for the Windows Live sites use this technique &#8211; every source file contains a function call at the bottom that tells a central notifier that it has been loaded.  Other code can ask the notifier to signal them when a file or set of files have been loaded.  This works in all browsers without relying on diverging browser idiosyncracies. </p>
<p>Unfortunately, this also requires that all the JavaScript you want to load dynamically (using this technique) knows about your particular load notification pattern.  If you want to dynamically load JavaScript from multiple libraries or authors, you will either end up with multiple notification systems (which should coexist peacefully) or you&#8217;ll have to modify those files to use your load notifier.  This is bad from a design standpoint because it requires that all your code modules have carnal knowledge of your application - erodes the modularity of the source files &#8211; or require that all your code modules follow the design patterns of a particular JavaScript toolkit, like DoJo or Prototype or YUI.  The latter isn&#8217;t a terrible tradeoff except that it limits your options.</p>
<p> Discovered via a note by <a href="http://www.stevetrefethen.com/blog/">Steve Trefethen</a> on <a href="http://www.friendfeed.com">FriendFeed</a>.</p>
<p><a class="a2a_button_twitter_tweet addtoany_special_service" data-count="none" data-url="http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/" data-text="Cross-Browser Dynamic JavaScript Loading"></a><a class="a2a_button_google_plusone addtoany_special_service" data-annotation="none" data-href="http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/"></a><a class="a2a_button_facebook_like addtoany_special_service" data-href="http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/"></a><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fdannythorpe.com%2F2008%2F07%2F23%2Fcross-browser-dynamic-javascript-loading%2F&amp;title=Cross-Browser%20Dynamic%20JavaScript%20Loading" id="wpa2a_16">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://dannythorpe.com/2008/07/23/cross-browser-dynamic-javascript-loading/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Cross-Domain Communication Using Domain Lowering</title>
		<link>http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/</link>
		<comments>http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/#comments</comments>
		<pubDate>Fri, 28 Sep 2007 08:52:28 +0000</pubDate>
		<dc:creator>Danny Thorpe</dc:creator>
				<category><![CDATA[Windows Live Quantum Mechanics]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[domain lowering]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[subdomain]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[More than a few blog posts ago I stated my intent to publish a series of articles on cross-domain communication techniques.  More time has passed than I had intended, but at last here is the start of that series of articles.  The series will explore progressively more advanced cross-domain techniques as well as their strengths <a href='http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p><a href="/2007/06/18/secure-cross-domain-communication-the-architecture-journal/">More than a few blog posts ago</a> I stated my intent to publish a series of articles on cross-domain communication techniques.  More time has passed than I had intended, but at last here is the start of that series of articles.  The series will explore progressively more advanced cross-domain techniques as well as their strengths and weaknesses, culminating in an announcement about stuff we&#8217;ve been working on that I think you&#8217;ll find interesting.</p>
<p>Cross-domain communication is usually discussed in the context of a browser client communicating to a web server that is different than the domain of the web page currently shown in the browser.  The browser client displays a page from server foo.com, and that page tries to access data on server bar.com.  This is forbidden by the same-origin browser security policy because bar.com isn&#8217;t foo.com.</p>
<h4>Server Side Proxy</h4>
<p>One relatively simple way to resolve this is to have the browser page request data from the page&#8217;s web server, and have the web server relay that request to the actual third party server.  The browser displays a page from foo.com, and that page makes a data request to foo.com which foo.com relays to bar.com.  Bar.com replies to foo.com, and foo.com forwards that response on to the browser client page to complete the circuit.</p>
<p>While this solution is simple and quite widespread today, it has some significant problems:</p>
<ol>
<li><strong>Scalability and Network costs</strong>:  The request and response travel across your server&#8217;s network twice.  Request in, request out, response in, response out.  Traffic on your server network grows four times faster than growth of your application use.  That means you&#8217;ll reach network saturation four times sooner than with other techniques, and you&#8217;ll pay four times more (in server network traffic costs) for the privilege.</li>
<li> <strong>Impersonating the user</strong>:  When your foo.com server makes a request to bar.com seeking data for the user, you&#8217;re essentially impersonating the end user.  If the data on bar.com requires any sort of user identification or authorization, your server side proxy suddenly jumps from super simple to super difficult.  It&#8217;s easy enough to ask the user to log in to bar.com, but your foo.com can&#8217;t see anything that goes on in bar.com.  In particular, foo.com cannot see whatever browser cookies that bar.com sets to indicate logged in state.  Thus, it will be next to impossible for foo.com to present the appropriate cookies or credentials in its http request to bar.com to make bar.com believe that the request is coming from the legitimate user.  And this should be difficult &#8211; this is nothing short of a man-in-the-middle attack on bar.com&#8217;s security!</li>
</ol>
<p>So, server side proxies are a quick and dirty way to toss anonymous data around, but they don&#8217;t scale well and they hit a wall when the data requires authentication.</p>
<h4>Web Sites With Subdomains</h4>
<p>Web sites and web applications generally start out as simple beasts running on a single web domain (www.foo.com).  As the site grows in functionality and complexity, the incentives to break that site up into subdomains (downloads.foo.com, feedback.foo.com, images.foo.com) grows as well.  Perhaps your web site has a download area that needs to be optimized for large file transfers.  That would probably be easier to fine tune as a server or cluster dedicated to that function than to try to tune the entire web site for large file downloads.</p>
<p>Subdomains often sprout as a byproduct of a company&#8217;s internal structure.  It takes a lot more effort to coordinate updates to one central server shared by multiple departments on different schedules than for a department to own their own subdomain, nicely isolated from the rest of the company&#8217;s constant revisions.</p>
<h4>Double Edged Sword</h4>
<p>Domain isolation is convenient to let you get your work done independently of the noise going on in the rest of the company&#8217;s web presence, but also presents a new problem:  web pages served from your subdomain cannot share information with web pages served from other subdomains of your company.  If the user logs in to your company&#8217;s main page, the browser cookies representing that login state are not accessible to your subdomain.</p>
<h4>Lowering the Domain Barrier</h4>
<p>The major browsers support a technique around this quandary, to allow subdomains to operate as equals within a common shared context.  The HTML document object has a domain property which normally reflects the complete domain name of the server from which the HTML document was loaded. The browser will allow you to assign a subset of the current domain name to the document.domain property to indicate that you wish for the HTML document to be treated as though it were loaded from the parent domain.</p>
<p>So, an HTML page served from downloads.foo.com can assign document.domain = &#8220;foo.com&#8221; in a JavaScript code block.  From that point forward, browser domain security checks will treat that page as a peer of any page in the foo.com domain.</p>
<p>The browser will (should) only allow you to change the document.domain to a less specific version of your current domain.  one.two.three.foo.com could be lowered to foo.com, or could be lowered to three.foo.com.</p>
<p>The browser should not allow assignment of a top-level domain (domain suffix) to document.domain.  You should not be able to change a document domain from &#8220;one.foo.com&#8221; to &#8220;com&#8221;.  There have been browser bugs in this area in the past where a browser implementer mistakenly interpreted &#8220;top level domain&#8221; to mean &#8220;the bit of the domain after the last dot&#8221;.  &#8220;.com&#8221;, &#8220;.edu&#8221;, and &#8220;.org&#8221; are top level domains, but &#8220;.co.uk&#8221; and &#8220;.co.jp&#8221; are TLDs also.</p>
<p>The browsers will not allow you to raise the domain of an HTML document to something more specific than its domain of origin, nor allow lateral domain shuttling.  Changing document.domain from &#8220;two.foo.com&#8221; to one.two.foo.com&#8221; is forbidden.  Changing a document.domain from &#8221;one.foo.com&#8221; to &#8220;two.foo.com&#8221; is forbidden.</p>
<h4>Irreversible (Mostly)</h4>
<p>Firefox 1.5 and 2.0 will not allow you to assign a domain name that is more specific than the document&#8217;s current domain name under any circumstances.  Once you lower one.foo.com to foo.com, it&#8217;s stuck at foo.com forever.  The only way to clear that state is to reload the page.</p>
<p>IE6 and IE7 will allow you to raise a document&#8217;s domain back to it&#8217;s actual domain of origin.  If a page was served from one.foo.com, and you lower it to foo.com, IE will let you raise it back to one.foo.com.  However, I&#8217;ve seen some instabilities and inconsistencies in the aftermath of &#8220;raising shields&#8221;, so I don&#8217;t recommend relying on this behavior.  Since Firefox doesn&#8217;t allow restoring domains to their original values, you should ignore the fact that IE sort of does allow it.</p>
<h4>Bridging Silos Via Least Common Denominators</h4>
<p>When an HTML document&#8217;s domain is lowered to a parent domain, the security context and JavaScript symbol space of that document joins the security context and JavaScript symbol space of any and all pages that are also in the parent domain.  JavaScript in your page served from one.foo.com and lowered to foo.com can access JavaScript functions and variables defined in other pages whose domain is foo.com, and visa-versa.</p>
<p>So, if you have pages on one.foo.com that would like to interoperate with pages on two.foo.com, you can use domain lowering to pull down the domain barriers just enough to allow them to talk to each other, but still provide domain protections against third parties trying to steal or corrupt the internal state of your web app.  Place a JavaScript block at the top of each page in the &#8220;one&#8221; and &#8220;two&#8221; subdomains which assigns document.domain = &#8220;foo.com&#8221; and you&#8217;re good to go.  All the pages will operate as though they were served from the same domain, and can access anything in each other&#8217;s DOMs and JavaScript symbol space.</p>
<h4>One or the Other, Not Both</h4>
<p>Note that once your one.foo.com page has been lowered into the parent domain, your HTML and JavaScript code loses all access to DOMs and JavaScript data in any other pages that are still in the original one.foo.com subdomain.  A web page can only be in one domain context or the other, not both.</p>
<h4>Interesting Inconsistencies</h4>
<p>Domain lowering applies only to the DOM and JavaScript sandboxes.  Parts (actually, nearly all) of the browser execute in native machine code outside the browser security sandbox. Native objects exposed to JavaScript in the sandbox are largely on their own to implement appropriate security checks on operations initiated by JavaScript.  JavaScript can&#8217;t access the local file system, for example, but if the user installs an ActiveX control for IE or a browser plugin for Firefox that allows local file access, and that extension declares itself safe for scripting, then JavaScript could use that control to access files on the local file system.</p>
<p>In both IE and Firefox, XMLHttpRequest (XHR) is a native object exposed to JavaScript.  This is pretty obvious in IE6 since you have to construct the object using ActiveXObject; in Firefox you can deduce that the XHR is a native object from the phrasing of some error messages and error behaviors while the browser goes down in flames.</p>
<p>XHR is restricted to connecting only to the current HTML page&#8217;s domain of origin.  Domain lowering applies only to the browser sandbox.  XHR operates outside the browser sandbox, enforcing same-origin domain policy on its own. This leads to an interesting &#8211; and valuable &#8211; inconsistency:</p>
<p><strong>XMLHttpRequest is not affected by domain lowering</strong>.</p>
<p>This means you can actually have one foot in each domain:  Your JavaScript executes in the context of the lowered subdomain (foo.com), but XHR requests made by your JavaScript are held to the domain restriction of the page&#8217;s original subdomain (one.foo.com). XHR doesn&#8217;t know anything about document.domain.</p>
<p>If you&#8217;re trying to get your JavaScript to open an XHR to a resource on foo.com, this can be infuriating because XHR won&#8217;t do it.  You have to refer to an HTML page served from foo.com in order to get XHR to open a connection to foo.com.</p>
<h4>The Money Shot</h4>
<p>This inconsistency in the handling of document.domain enforcement/awareness makes the following scenario possible:  The logic of your web app runs in the context of a page loaded from one.foo.com, and you want to XHR load data from two.foo.com.</p>
<p>Here&#8217;s how you do that:</p>
<ol>
<li>Make your html page A served from one.foo.com lower its document.domain to foo.com</li>
<li>Place an html page B on two.foo.com, and have it lower its document.domain to foo.com early in its load cycle.  (A JavaScript statement in global scope in the &lt;head&gt; section is fine).</li>
<li>Implement a function GetData(callback) on this page that constructs an XHR request to load the desired data from two.foo.com.  Wire up the XHR onReadyStateChanged to process the data completion using a function implemented in B.html, and in that function pass the received data to the callback function passed into GetData().</li>
<li>Insert an invisible (1&#215;1 pixel) iframe on page A and set its src to http://two.foo.com/B.html</li>
<li>After page A has fully loaded, and page B in the iframe has loaded, JavaScript code in page A can call the GetData() function in page B through the iframe element:  bframe.window.GetData(mycallback)</li>
</ol>
<p>Believe it or not, this works. Domain lowering allows JavaScript to call between A and B, and the fact that B is served from two.foo.com allows the XHR request implemented in B to access two.foo.com.</p>
<h4>Here Be Pixies.  (Try Not To Piss Them Off)</h4>
<p>The path through this murky realm is neither straight nor wide.  If you take liberties or shortcuts with this recipe, be careful to test your code thoroughly on multiple browsers.  Chances are high that any deviation will lead to failure on one of the browsers.</p>
<p>IE is fairly flexible in this area.  You don&#8217;t actually have to implement the GetData function in the B page.  You can just construct in the A context an XHR object type from the B context and use it directly in the A context.  ( var xhr = new bframe.window.XMLHttpRequest() )  For IE, the B page need only lower the domain to foo.com.  After that, all the driving can be done from A.</p>
<p>Firefox is more particular about this technique.  Firefox will allow you to construct an instance of the B XHR in the context of A, but you&#8217;ll get access denied or weirder errors when you try to call the methods of the B XHR from the context of A.  Firefox gets confused when you call native object methods across these convoluted domain bridges, but calling JavaScript functions and methods works fine on either side of the context boundary.  Once the JavaScript call context gets from A to B, then the native object method calls will work.</p>
<p>This is also why step 3 above mandates that the XHR onReadyStateChange event handler should be wired to a function implemented in the B page &#8211; the native XHR object operating in the B context may have difficulty firing an event wired to a function in the A page context.</p>
<h4>The Downside to Homogeneity</h4>
<p>For domain lowering to work between two subdomains, both sides have to &#8220;lower their shields&#8221; to a common middle ground. As this technique catches on across departments and their corresponding subdomains, you can quickly reach a point where just about all the subdomains on the corporate web have provisions to lower their domain to the common corporate parent domain.</p>
<p>This is convenient and quite powerful for building web apps that can access data bits from all across the company.  The problem is that it weakens your corporate defenses across the board.  If just one of the subdomain silos were compromised and an attacker were able to inject malicious JavaScript to execute in the browser context of that compromised subdomain, that malicious code would have easy access to every subdomain across the company that lowers its domain to foo.com.</p>
<p>This risk grows with scale.  The more subdomains you have that routinely lower their domains to the common ground, the greater the risk that one of them may be compromisable and serve as a beachhead to your entire network.</p>
<h4>Tune In Next Time</h4>
<p>There is a way to mitigate this weakest link risk such that an attacker compromising a weak subdomain does not get access to everything.  This requires inverting some of the relationships presented in this article and making the silos deeper rather than shallower.  I&#8217;ll cover &#8221;Siloed Domain Lowering&#8221; in my next cross-domain article.</p>
<p><em>Originally published on my <a href="http://blogs.msdn.com/b/dthorpe/archive/2007/09/27/cross-domain-communication-using-domain-lowering.aspx">MSDN blog</a>.</em></p>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=5180444" alt="" width="1" height="1" /></p>
<p><a class="a2a_button_twitter_tweet addtoany_special_service" data-count="none" data-url="http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/" data-text="Cross-Domain Communication Using Domain Lowering"></a><a class="a2a_button_google_plusone addtoany_special_service" data-annotation="none" data-href="http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/"></a><a class="a2a_button_facebook_like addtoany_special_service" data-href="http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/"></a><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fdannythorpe.com%2F2007%2F09%2F28%2Fcross-domain-communication-using-domain-lowering%2F&amp;title=Cross-Domain%20Communication%20Using%20Domain%20Lowering" id="wpa2a_20">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://dannythorpe.com/2007/09/28/cross-domain-communication-using-domain-lowering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  dannythorpe.com/tag/javascript/feed/ ) in 0.51030 seconds, on May 21st, 2012 at 5:45 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 21st, 2012 at 6:45 pm UTC -->
