Javascript checking for file on different web site

I just had one of those “shouldn’t this be easier” moments.  I had some client-side Javascript that needed to do something different based on whether or not a file existed on another website (basically to choose what URL to pass to the Flash Player).  Server-side coding was not an option; I just had an HTML file to work with.  I thought it would be easy…but then I didn’t consider the cross-domain scripting security in the browsers!

I tried a few options:

  1. Using XMLHttpRequest to check for the existence of a file – this would be the cleanest way if the file was in the same domain as the HTML file, but XMLHttpRequest is usually blocked for cross domain calls. It worked on IE8 if the setting “Access data sources across domains” was enabled, but did not work in IE7 or Firefox
  2. Using an IFRAME on the page and communicate via URL fragments – this is a complicated trick that sites like Facebook use to address similar issues. The coding is complex, however, and can have impact on the Back button and things. (See http://msdn.microsoft.com/en-us/library/bb735305.aspx or http://wiki.developers.facebook.com/index.php/Cross_Domain_Communication)
  3. Using JSON calls to a service on the second server – browser security does allow calls to a web service on a different domain, but this would require putting code on that second server.  This was not an option.

So I had to resort to a little less elegant approach, but one that requires minimal scripting and works across browsers.  Nothing prevents us from pulling an image from another website, so we can place a 1×1 transparent gif on the other website as a “marker” for the file we are looking for.  Then we simply put the img tag on our page and respond to the onload and onerror events.

<img src='http://otherwebsite.com/marker.gif' onload='DoIfItsThere();' onerror='DoIfItsNotThere();' style='visibility:hidden' />

While placing a marker file on other websites may not always be an option, this approach could be used to check whether that site is available.  Want to see if Google is running?  Just pull down the Google logo and if it works, it’s working!  (Yes, bad example because Google has web services we could call.  But you get the point)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s