javascript - Client-side website reachability test -


i building facebook application runs through apps.facebook.com system. question not facebook apps (so don't stop reading if not familiar these) you'll see why important shortly.

whenever user wishes use app, go firstly standard website (with more memorable address, let's use example xyz.com) automatically redirect facebook application. however, there 2 possible redirection destinations:

  1. to standard facebook application page (e.g. apps.facebook.com/xyz). should occur if client can reach page. importantly, reason client may not able reach page if on network running content filter (e.g. schools, universities, workplaces) blocks facebook.

  2. if client cannot reach facebook application page should redirected page on main website (e.g. xyz.com/nofacebook_login.html).

as can see, redirection decision needs based upon whether client can reach facebook application page, or not. therefore, testing need occur on client-side (presumably) using javascript, jquery, or similar. however, unsure how go this.

any suggestions appreciated.

the obvious solution (just send ajax request remote domain , see response) doesn't work due same-origin policy.

you ask facebook implement cross-origin resource sharing protocol. if agree, rest easier. if not, however, $.ajax - or native xmlhttprequest - won't do.

however, while xhrs subject same-origin policy, other ways send http request not: can create image src of image on apps.facebook.com, , see if loads. problem here facebook serves of content akamaihd.net, unlikely co-blocked apps.facebook.com. did, however, find one image served apps.facebook.com: http://apps.facebook.com/images/spacer.gif (http://facebook.com/images/spacer.gif exists). @robw pointed me favicon (http://apps.facebook.com/favicon.ico)

to test if image can loaded:

  1. create new img element
  2. add load listener , error listener it, perform redirect
  3. set img src
  4. adding image document should not neccessary, haven't tested everywhere.
var img = document.createelement("img"); img.onload = function(){location.href = "http://apps.facebook.com/xyz"}; img.onerror = function(){location.href = "http://xyz.com/nofacebook_login.html"}; img.src = "//apps.facebook.com/favicon.ico"; //thanks @robw document.body.appendchild(img); 

note: facebook guarantee either image exist. while there seems decent chance stay, may disappear eventually. if happens, appear blocked (you may want check error code, don't know blockers return). if happens, please notify me or update answer new working image.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -