7

可能重复:
通过 JavaScript 检查网站是否启动的最佳方法是什么

我们即将通过我们的 Facebook 页面开展一项活动。理想情况下,我们希望我们用于此活动的网址(例如 www.oursite.com/campaign)将所有流量重定向到我们的 Facebook 网址(例如 www.facebook.com/example)。但是,许多工作场所网络会阻止社交媒体网站,因此在自动重定向之前,我想先检查用户的网络是否允许 Facebook:如果是,则重定向到 Facebook;如果没有,请继续访问我们的网址 (www.oursite.com/campaign)。

任何帮助将不胜感激,

Ryan(我对 PHP 没问题,从新到 javascript)

4

1 回答 1

12

Facebook SDK method

Since you need to check if the user has access to facebook you could try to initialize the the Facebook SDK and base your logic on that

According to documentation window.fbAsyncInit function is called on a successful initialization of the SDK, so you might achieve your effect with something like this:

var campaignLink = "http://www.oursite.com/campaign";

window.fbAsyncInit = function() {
    // facebook sdk initialized, change link
    campaignLink = "http://www.facebook.com/example";
}

Please note that this is all theoretical and untested, you might need to read more here

https://developers.facebook.com/docs/reference/javascript/

Favicon method

This function tries to load the favicon.ico file of the supplied URL and takes it as an indicator on whether the site is accessible (by the user) or not. It assumes that a site has a favicon, but you could easily change that to another image which you know exists.. (example the facebook logo)

function isSiteOnline(url,callback) {
    // try to load favicon
    var timer = setTimeout(function(){
        // timeout after 5 seconds
        callback(false);
    },5000)

    var img = document.createElement("img");
    img.onload = function() {
        clearTimeout(timer);
        callback(true);
    }

    img.onerror = function() {
        clearTimeout(timer);
        callback(false);
    }

    img.src = url+"/favicon.ico";
}

Usage would be,

isSiteOnline("http://www.facebook.com",function(found){
    if(found) {
        // site is online
    }
    else {
        // site is offline (or favicon not found, or server is too slow)
    }
})
于 2012-12-01T23:34:06.743 回答