How To Check 404 Not Found URL Status in Javascript Tutorial

Share this Article
Reading Time: 3 minutes
200 Views

Inside this article we will see the concept i.e How To Check 404 Not Found URL Status in Javascript Tutorial. Article contains the classified information about How to check if url returns 404 error status using javascript.

If you are creating an application in which you want to check whether a URL returns a HTTP status code 404, then you can use this concept to your code. You will get the very basic and super easy concept to do this.

Learn More –

Let’s get started.

Application Programming

Let’s create a folder with name check-page in your localhost directory. In this project folder, create a file: index.html

Open index.html and write this complete code into it.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How To Check 404 Not Found URL Status in Javascript Tutorial</title>
</head>

<body>

    <script>
        var url = "Put Your URL Here...";

        UrlExists(url);

        // User helper function to Check Page Status
        function UrlExists(url) {
            var http = new XMLHttpRequest();
            http.open('HEAD', url, false);
            http.send();
            if (http.status != 404)
                console.log("Exists");
            else
                console.log("Not Found");
        }
    </script>
</body>

</html>

Concept

We used XMLHttpRequest() javascript method. It provides the status code property. For “Not Found”, error code is 404.

function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status != 404)
        console.log("Exists");
    else
        console.log("Not Found");
}

Application Testing

Open your browser.

Next,

Your project URL will be like this.

URL: http://localhost/check-page/index.html

You will see your output into browser’s console.

We hope this article helped you to learn How To Check 404 Not Found URL Status in Javascript Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Get PHP Web Development Courses on Offer in just ₹299
Get PHP Web Development Courses on Offer in just ₹299