Checking if a URL is broken in Javascript

后端 未结 2 2001
名媛妹妹
名媛妹妹 2020-12-02 17:38

This question has been posted on Stack before, but none so specific as to what I\'m trying to understand.

The simplest way to check if a URL is corrrect to send a ht

相关标签:
2条回答
  • 2020-12-02 18:09

    Modern, cross and short way

    checkLink = async url => Boolean(url) || (await fetch(url)).ok
    

    which is same of:

    async checkLink(url) { return Boolean(url) || (await fetch(url)).ok }
    

    which is same of:

    async function checkLink(url) { return Boolean(url) || (await fetch(url)).ok }
    

    which is same of:

    Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0, and Edge 13, synchronous requests on the main thread have been deprecated due to their negative impact on the user experience.

    Cross solution (old, deprecated)

    function UrlExists(url) {
     var http = new XMLHttpRequest();
     http.open('HEAD', url, false);
     http.send();
     return http.status==200;
    }
    
    0 讨论(0)
  • 2020-12-02 18:12

    I'd recommend to use jQuery for correct cross-browser ajax requests:

    function UrlExists(url, cb){
        jQuery.ajax({
            url:      url,
            dataType: 'text',
            type:     'GET',
            complete:  function(xhr){
                if(typeof cb === 'function')
                   cb.apply(this, [xhr.status]);
            }
        });
    }
    

    Usage:

    UrlExists('/path/script.pl', function(status){
        if(status === 200){
           // file was found
        }
        else if(status === 404){
           // 404 not found
        }
    });
    
    0 讨论(0)
提交回复
热议问题