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

前端 未结 3 1091
礼貌的吻别
礼貌的吻别 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: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.

提交回复
热议问题