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:
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.
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:
- create new
img
element - add
load
listener ,error
listener it, perform redirect - set
img
src
- 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
Post a Comment