Have you ever clicked on a link on a website and got a "404 Not Found" page? If you have seen, these broken links are annoying not only for you but also for website owners. Because they negatively affect the user experience and even search engine rankings. This is why a broken link checker tool is needed, it automatically scans your website to find and fix dead links before they cause problems.

If you are a new or pro web developer, building your own broken link checker is a fun project. Because it will help you improve your skills in using HTML, CSS and JavaScript. In this project we won't be using any complex Javascript, just simple web technologies that you probably already know.

So in this article, I will teach you how to create a simple but effective broken link checker tool that you can run directly in your browser.

What are the benefits of link checking?

Using Link Checker makes it easy to keep your site healthy. Instead of manually clicking each link, the tool automatically scans your entire website. It shows you which links are working and which aren't, so you can fix them quickly. This helps keep your site fast.

What logic do we build on?

Users input a website URL into our tool. Then clicking the button below will automatically scan all the hyperlinks (<a href="broken link">) on that page. It will report which links are valid and which ones are broken. will show the results in a clear list.

Below is a live demo that will help you understand how the Broken Link Checker Tool UI Design.

Live demo:

HTML
CSS
JS
Result

HTML:

We will start by adding an <h1> heading element to clearly communicate the purpose of our tool. Next we will set up an input element where users can type in the URL of the website they want to scan.

Below the input, we will add a <button> element with the text "Scan Links". This button will be useful in our JavaScript later, as clicking on it will start the scanning process.

Finally, we will add a <div> element with the ID "results". It acts as a container where the broken link scan result will show. ie show the user which links are working and which are broken.

<h1>Broken Link Checker</h1>

<input type="text" id="urlInput" placeholder="https://example.com" size="50">
<button id="checkLinks">Scan Links</button>

<div id="results"></div>

Stylesheet (CSS):

Setup the body and heading:

By setting the css flex-direction property to column and flex to display we'll set the content inside the body vertically. The justify-content property helps to center containers along the vertical axis.

We choose the Arial, sans-serif font family for a clean look that's easy to read on a variety of devices. We set a max width of 800px and center the entire layout with margins to avoid stretching everything too much on large screens. Set the background color to light gray (#f9f9f9), and the text color to a dark gray (#333) for a softer look.

For headings we center the text by centering the text-align propeoity so that it stands out clearly at the top of the page. The color is dark blue-grey (#2c3e50) which will give it a professional feel.

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: 40px auto;
    padding: 20px;
    background-color: #f9f9f9;
    color: #333;
}

h1 {
    text-align: center;
    color: #2c3e50;
}
Styling the input and button:

We start by styling the text input field into which the user will type the URL. Added 10px padding to the input so the text doesn't shrink and set the font size to 1em for easy readability.

Next we style the button where the button rule applies padding around the text to make it easier to click and sets the font size to 1em so the text is readable. The background color is set to a beautiful blue color (hex code #3498db). We also apply a 5px border-radius so that the corners of the button are rounded and use the CSS cursor property so that the cursor changes to a pointer when it is rotated.

Finally we add a hover effect to the button. When the user moves their mouse over the button, the background color darkens a little (Hex code #2980b9).

input[type="text"] {
    padding: 10px;
    font-size: 1em;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
}

button {
    padding: 10px 20px;
    font-size: 1em;
    margin: 10px;
    border: none;
    background-color: #3498db;
    color: white;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #2980b9;
}
Styling the results:

Before going to the #results section, we start with some white space with margin-top 20px, so it's not too close to the top button. The background color is set to pure white (hex code #fff), which makes it stand out against the light gray background of the page.

To make the result area look like a card, we add padding 20px. The corners are slightly rounded with a radius border of 8px.

#results {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

#results p {
    line-height: 1.5;
    font-size: 1em;
}

.valid {
    color: green;
}

.broken {
    color: red;
}

JavaScript:

Using a CORS Proxy

We will start by writing Javascript code using CORS proxy, and our project cannot be completed without CORS proxy. A CORS proxy is a service that allows your browser to access content from other websites.

Browsers prevent scripts from fetching data from other domains unless the server explicitly allows it, called the Same-Origin Policy. A CORS proxy works by fetching content on its own server and then sending it back to your browser with the required permissions. This way you can safely retrieve and use data from other sites without experiencing cross-origin errors.

We will use the following CORS proxy in this project:

const corsProxy = 'https://api.allorigins.win/get?url=';

We will use the "allorigins" proxy here to get data from the site. If this proxy stops working in the future, you can easily switch to another similar service. Creating such a project on localhost will not cause much problem. Simply put it acts as a bridge, allowing your web application to access resources it otherwise couldn't.

DISCLAIMER: This project is intended for educational purposes only. Please remember Check that you have permission to access and use information from external websites and always abide by their terms of service. Do not use private or copyrighted content without explicit consent. CodeHemu is not responsible for any misuse of this tool or violation of third party policies.

Link Checker Works in Real Time:

Now the most important part is to test the links one by one and show the results in real time. If you learn how this JavaScript works, you will easily be able to create similar tools in the future without any trouble. So let us get started.

First we created an async function called results, which takes as input a list of links. Inside the function we use a special technique "[...new Set(links)]" to remove any duplicate links because there is no need to check the same link twice.

Then we use a "for...of" loop to visit each link one by one. For every link we try to send a request using "fetch()". But since browsers don't allow us to directly fetch data from other websites due to security rules, we use a CORS proxy to help fetch content.

When the response is returned we check "resultData.contents" to see if it contains valid content. If the content exists we mark the link as valid with a nice green checkmark.

If it doesn't or something is wrong, we will mark the link as broken with a red cross.

All results are displayed in real time inside the results area of the page, so you don't have to wait until everything is finished.

const resultsDiv = document.getElementById('results');

async function results(links) {
    for (const link of [...new Set(links)]) {
        try {
            const response = await fetch(corsProxy + encodeURIComponent(link));
            const resultData = await response.json();
            if (resultData.contents) {
                resultsDiv.innerHTML += `<p class="valid">Valid: ${link}</p>`;
            } else {
                resultsDiv.innerHTML += `<p class="broken">Broken: ${link}</p>`;
            }
        } catch (err) {
            resultsDiv.innerHTML += `<p class="broken">Error: ${link} (${err.message})</p>`;
        }
    }
}
Adding the click event:

Last, we added a click event to our "Scan Links" button. That means when you click on it, the script first takes the URL you entered in the input box and makes sure it's not empty. If the URL is valid then we display a message saying "Fetching links..." when the process starts.

Then using the CORS proxy, we send a request to get the full HTML content of the target website. Once we receive the response, we use a DOMParser to convert the HTML into a document.

Next, we collect all the links from that page and convert them to full URLs. We display a message showing how many links we found and call the result function to check each link one by one in real time.

If something goes wrong during this process we display an error message to let the user know that something has failed.

document.getElementById('checkLinks').addEventListener('click', async () => {
    const targetUrl = document.getElementById('urlInput').value.trim();
    if (!targetUrl) return alert('Please enter a valid URL.');

    resultsDiv.innerHTML = '<p>Fetching links...</p>';

    try {
        const res = await fetch(corsProxy + encodeURIComponent(targetUrl));
        const data = await res.json();
        const html = data.contents;
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');

        const links = Array.from(doc.querySelectorAll('a[href]'))
            .map(a => new URL(a.getAttribute('href'), targetUrl).href)
            .filter(url => url.startsWith('http'));

        resultsDiv.innerHTML = `<p>Found ${links.length} links. Checking...</p>`;

        results(links);

    } catch (error) {
        resultsDiv.innerHTML = `<p class="broken">Failed to fetch page: ${error.message}</p>`;
    }
});

Answering common questions, ‘How to overcome CORS error?’
– To avoid CORS errors in JavaScript, you can use a CORS proxy. It acts like an intermediary that fetches data from other sites for you and sends it back with proper permissions. You just need to make sure that you have permission to use data!

‘How to remove duplicate elements in an array in JavaScript?’
– You can use a Set to remove duplicates, like this [...new Set(array)].

Are you interested in CSS art? CSS Fish Animation | CSS Art

Today we are ending the youthful button effect tutorial here, and if you have any questions about the youthful button effect, you can share your feelings in the comments. You can follow our YouTube channel to get more updates about the CODEHEMU tutorial. I ended the tutorial by saying Nomoskar to the you.

Post a Comment

Previous Post Next Post