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();
});
}