Checking if the Internet and a particular site are up in JavaScript/AJAX

前端 未结 3 1092
礼貌的吻别
礼貌的吻别 2021-01-24 17:09

I have a page which runs locally on my device, and I would like to use AJAX or normal JavaScript to check if the device is connected to the Internet and if a pa

相关标签:
3条回答
  • 2021-01-24 17:41

    There is basic support for

    navigator.online
    //Events
    window.onOnline
    window.onOffline
    

    on desktop browsers and support on Android. This might not completely answer your question, but I thought its worth sharing anyway :)

    0 讨论(0)
  • 2021-01-24 17:43

    Unlike Ajax, the loading of scripts and images is not subject to the same-origin policy, so you can query for their existence (but not read their contents) cross-domain. If you know a particular image on the site, you can use the onload event handler of a new Image to test if a site is up:

    var i = new Image();
    i.onload = function() { alert("site is up!") }
    i.onerror = function() { alert("site is not up!") }
    i.src = "/favicon.ico";
    

    /favicon.ico is on a huge number of major sites, since it's required for favicon functionality in older IE. Not every site of the Web has it (indeed, not every site on the Web has a favicon), but it will work for major sites like Google, Wikipedia, Stack Overflow, etc.

    /favicon.ico is nice for cross-site support, but if you only want to target one specific site, simply find an image on that site and query for its existence.

    0 讨论(0)
  • 2021-01-24 17:52

    Cross site Ajax is forbidden due to security concerns. A few work arounds would be to either use greasemonkey/userscripts(if this is just for personal use), or a plugin such as flash or java

    0 讨论(0)
提交回复
热议问题