Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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!)

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda