JSFiddle - React, Tailwind, and code Playground
HTML
<a name="anchor" href="here.html" onclick="checkLink(this, event)" >local link</a>
<a href="#anchor" onclick="checkLink(this, event)" >anchorlink</a>
<a href="http://www.google.com" onclick="checkLink(this, event)" >external link(checked)</a>
<a href="http://www.google.com" >external link (unchecked)</a>
JavaScript
window.onbeforeunload = function(event){
//you can't access the destination here
console.log(JSON.stringify(event))
console.log(event.returnValue, event.target, window.location);
var s = "test string";
//return something
event.returnValue = s
return s
}
window.checkLink = function (link, event){
console.log("navigating to", link.getAttribute("href"), link.href, event);
var href = link.getAttribute("href");
if(href[0] == "#")
return true;//anchor link
if(href.match(/^http(s)?:\/\//i)){
//user clicked on an external link
if(!confirm("are you sure??? (special string)")){
//user cancelled
event.preventDefault();
return false;
}
//user confirmed
//disable onbeforeunload
}
window.onbeforeunload = function(){}
//link is ok, proceed
return true;
}