1

Is there a way to make a call to a website when clicking a button, without actually visiting the website?

While the following allows me to click the link without visiting the page, it doesn't actually ping http://example.com.

<a href="http://example.com" onClick="return false;">Click here</a>

2 Answers2

1

There is a specific tag attribute for this purpose. It is called ping.

When the user clicks on the hyperlink, the ping attribute will send a short HTTP POST request to the specified URL.

You can use it this way:

<a href="javascript:void(0)" ping="http://example.com">Click here</a>

Unfortunately, it is not supported by IE, Edge and Safari.

Dino
  • 6,207
  • 8
  • 28
  • 62
Denys Kozak
  • 317
  • 3
  • 11
0

There are way to check the url are online or not, you can use XMLHttpRequest to interact with client between server without visiting the website.

bellow is the example how to implement XMLHttpRequest, for your html button:

<a href="https://example.com" onclick="return clickFunction(this);">Click here</a>

for your javascript function:

function clickFunction(element) {
  event.preventDefault();
  var url = element.getAttribute('href');
  onlineCheck(url).then(() => {
    // Has internet connection, carry on 
    alert("Has intenet connection")
  }).catch(() => {
    // Has no internet connection, let the user know
    alert('Sorry, no internet.');
  });  
}

function onlineCheck(url) {
  var xhr = new XMLHttpRequest();
  return new Promise((resolve, reject) => {
    xhr.onload = () => {
      resolve(true);
    };
    xhr.onerror = () => {
      reject(false);
    };
    xhr.open('GET', url, true);
    xhr.send();
  });
}
Ari Pratomo
  • 991
  • 10
  • 6