LOGI

JavaScript 检测站点能否访问

可以通过加载图片的方式检测站点是否可以访问,具体方法是处理 imgonloadonerror 事件,这意味着被测站点必须具有一张可以访问的图片。

<script>
    let websites = [
        'https://www.google.com/large/005BYqpgly1g0udmuyyh1j30u01o04dz.jpg',
        'https://www.baidu.com/img/dong_79c77bf7ad27549a653ed090b1a5d9d3.gif'
    ];

    document.addEventListener('DOMContentLoaded',
        () => websites.forEach(website => check(website,
            () => {
                let url = new URL(website);
                // 检测成功跳转主页
                location.href = url.protocol + '//' + url.host;
            }
        ))
    );

    function online(url) {
        let img = new Image();
        return new Promise((resolve, reject) => {
            img.onload = () => resolve(true);
            img.onerror = () => resolve(false);
            img.src = url + '?t=' + Date.now();
        });
    }

    function isFunction(funcName) {
        return typeof funcName === 'function' ? true : false;
    }

    async function check(url, success, failure) {
        let netState = await online(url);
        if (netState && isFunction(success)) {
            success();
        } else if (isFunction(failure)) {
            failure()
        }
    }
</script>

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »