I'm trying to make a pop-up that will prevent the user from going to the resulting page if they hit cancel. This code works in Chrome, Safari, Opera, Microsoft Edge, and Internet Explorer 11, but not in Firefox.
function leavingAlert(){
var check = confirm("You are about to leave the site! You may be going to a website that doesn't provide security. Do you wish to continue?");
if(check){
this.target="_blank"
return true;
}else{
event.cancelBubble = true;
return false;
}
}
//WORKING FOR ALL NON-IFRAME LINKS
var container = document.getElementById("wrapper");
var allATags = wrapper.getElementsByTagName("A");
for(var i = 0, len = allATags.length; i < len; i++){
var link = allATags[i];
//var pat = /^https?:\/\//i;
var pat = new RegExp("https://example.com");
var pat2 = new RegExp("javascript");
if(!pat.test(link.href)){
if(!pat2.test(link.href)){
link.onclick = leavingAlert;
}
}
}
I've also used these instead of event.cancelBubble with no luck:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
and
event.stopImmediatePropagation;
and
event.stopPropagation;
Where I am implementing this code I can't currently use jQuery so an answer in plain Javascript would be preferred thank you!
Using event
as a global variable is not standard Javascript, and it's not implemented in Firefox. It should be accessed as the argument to the onclick
handler.
function leavingAlert(event){
var check = confirm("You are about to leave the site! You may be going to a website that doesn't provide security. Do you wish to continue?");
if(check){
this.target="_blank";
return true;
}else{
event.cancelBubble = true;
return false;
}
}