js判断网站url是否可以正常访问

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js判断网站url是否可以正常访问</title>
    <script>
        function getXMLHttpRequest() {
            var client = getXMLHttpRequestFromIE();
            if (client == null) {
                client = new XMLHttpRequest();
            }
            return client;
        }
        function getXMLHttpRequestFromIE() {
            var namePrefixes = ["Msxml3", "Msxml2", "Msxml", "Microsoft"];
            for (var i = 0; i < namePrefixes.length; i++) {
                try {
                    var name = namePrefixes[i] + ".XMLHTTP";
                    return new ActiveXObject(name);
                } catch (e) {
                }
            }
            return null;
        }
        var client = null;
        //返回值   
        var stateString = "";
        //请求url的网站   
        function checkUrl(url) {
            client = getXMLHttpRequest();
            var actionURL = convertURL(url);
            try {
                client.open("GET", actionURL, true);
                client.onreadystatechange = callBack;
                client.send(null);
            } catch (e) { }
            finally {
            }
        }
        function callBack() {
            if (client.readyState == 4) {
                console.log(666.2001, client)
                stateString = client.responseText;
                if (stateString && client.status == 200) {
                    isRun = true;
                    document.getElementById("ceshi").innerText = "网站是可以访问的!";
                } else {
                    document.getElementById("ceshi").innerText = "网站不可访问!";
                }
            }
        }
        //给url地址增加时间戳,骗过浏览器,不读取缓存       
        function convertURL(url) {
            //获取时间戳       
            var timstamp = (new Date()).valueOf();
            //将时间戳信息拼接到url上   
            if (url.indexOf("?") >= 0) {
                url = url + "&t=" + timstamp;
            } else {
                url = url + "?t=" + timstamp;
            }
            return url;
        }
        // checkUrl("https://www.baidu.com");

        function urlOk(e) {
            console.log(666.1001, e)
        }
        function urlError(e) {
            console.log(666.1002, e)
        }
    </script>
</head>

<body>
    <div id="ceshi"></div>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" onload="urlOk(event)" onerror="urlError(event)" />
</body>

</html>
  • 暂不支持跨域自处理,需要在服务器上配置跨域白名单

你可能感兴趣的:(javascript,前端,开发语言)