user3358102
user3358102

Reputation: 317

Check if url is working and if so do something

I found the following solution Checking if a URL is broken in Javascript

In the answer it says to use

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

to check if a url is available.

So let's assume I would like to display a message in case a url is working so I wrote:

let url = 'https://www.example.com/index.html';
if(checkLink = async url => (await fetch(url)).ok) {alert ("Hello world!");};

Unfortunately the above code always shows the alert message no matter if the url is available or not. How can I use this code to test if a url is valid.

Upvotes: 0

Views: 425

Answers (2)

user19430065
user19430065

Reputation:

If you are looking to use an input field or something of the sorts, you can use checkValidity(). https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity

<html>
  <body>
    <script>
      function validation() {
        const inp = document.getElementById("url");
        const p = document.getElementById("text");
        if(!inp.checkValidity()){
          p.innerText = inp.validationMessage;
        }
      }
    </script>
    <form>
      <input id="url" type="url" placeholder="URL Here">
      <input type="submit" value="Submit" onclick="validation()">
    </form>
    <p id="text"></p>
  </body>
</html>

Upvotes: 0

Robin Zigmond
Robin Zigmond

Reputation: 18249

With the function definition you gave

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

you would typically use this as follows.

async function doStuff() {
  let url = 'https://www.example.com/index.html';
  let doesLinkWork = await checkLink(url);
  if (doesLinkWork) {
    alert("it works");
  } else {
    alert("it doesn't work");
  }
}

and then call doStuff from the console or from somewhere else in your code. (Obviously that function name is just an example - you should call it something more appropriate to what you actually want it to do!)

Upvotes: 2

Related Questions