How to display a warning message before leaving site by clicking on tab in chrome? - javascript

I am trying to warn the user before closing the tab. I search on many places for the right code but It seems that it doesn't work in chrome.
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>
In IE it works fine. I don't need to display any custom message. I just need to warn the user that they will leave the site. Any idea why this doesn't work? Is there any other way to force the browser to display warning before leaving site?
EDITED: I use Google Chrome version 74.0.3729.169

window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};

Use the confirm() function:
function confirmExit(e) {
if (!confirm("You have attempted to leave this page. Are you sure?")) {
e.preventDefault();
return false;
}
}

I found the solution thanks to #barbsan. The link that he provided contains the solution.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent

Related

Not able to remove the beforeunload event

We are using following code to show default pop up on refresh, tab close events
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
if ($('#timeExpiredtxt').hasClass('hide') && $("#submittedAnsResponseText").hasClass("hide")) {
var confirmationMessage = 'You are attempting an assessment. Are you sure you want to leave this assessment?';
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
}
});
I want to remove and unbind this event at runtime. I tried the following code but no luck.
$(window).off("beforeunload");
$(window).off("onbeforeunload");
window.onbeforeunload = null;
$(window).unbind("beforeunload");
Had to change the event binding code.
function closeIt() {
if ($('#timeExpiredtxt').hasClass('hide') && $("#submittedAnsResponseText").hasClass("hide")) {
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
}
window.onbeforeunload = closeIt;
and unbind used below code
window.onbeforeunload = null;

window.onbeforeunload not showing messages in chrome

I'm showing an alert message on certain conditions when an user tries to leave. The message is shown in Safari, but it doesn't work in Chrome.
I tried two things like following:
window.onbeforeunload = function(event) {
if ($scope.isFormChanged == true) {
event.returnValue = 'Don\'t go yet! Save your changed data before you leave!';
}
}
window.onbeforeunload = function() {
if ($scope.isFormChanged == true) {
return 'Don\'t go yet! Save your changed data before you leave!'
}
}
I think this works in chrome. And I have also doubt with isFormChanged.
<script type="text/javascript">
window.onbeforeunload = function() {
return "Are you sure you want to close window?"
}
</script>

Able to detect Ctrl+R But stop reloading page

I am able to detect Ctrl+R but unable to stop reloading page.
Please help me to fix this.
I am using this code.
$(document).keydown(function(e) {
if (e.keyCode == 65+17 && e.ctrlKey) {
alert('ctrl R');
exit;
return ;
}
});
Thanks in advance.
The standard / clean way to help user prevent unwanted page reload is via beforeunload and not via overriding key event, which is, in fact, futile: you do not know what key combination invoked page reload (for instance, f5 works alike in most browsers), he may press CTRL+R with locationbar focused so your page gets no event to capture, he may have pressed toolbar button…
Mentioned standard approach from linked MDN page
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
This will prompt user whenever he tries to reload / close / navigate away from your page no matter what initiated unload.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function () {
document.onkeydown = KeyPress;
function KeyPress(e) {
console.log(e);
var press = window.event? event : e
if (press.keyCode == 82 && press.ctrlKey) alert("Ctrl+R");
if ($.browser.mozilla) {
if (e.ctrlKey && keycode == 82) {
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
}
if ($.browser.msie) {
if (window.event.ctrlKey && press.keycode == 82) {
window.event.returnValue = false;
window.event.keyCode = 0;
window.status = "Refresh is disabled";
}
}
}
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

How do I detect popup blocker in Chrome?

I have searched many issue in stack overflow and might be duplicate here Detect Popup
But not helped for me while testing in Chrome (tested v26.0.1410.64)
Following Approach Worked in IE and Firefox but not in Chrome
var popup = window.open(winPath,winName,winFeature,true);
if (!popup || popup.closed || typeof popup.closed=='undefined'){
//Worked For IE and Firefox
alert("Popup Blocker is enabled! Please add this site to your exception list.");
window.location.href = 'warning.html';
} else {
//Popup Allowed
window.open('','_self');
window.close();
}
Any better solution that works for Chrome also?
Finally, it success by combining different answer from Stackoverflow's member
This code worked for me & tested in IE, Chrome & Firefox
var popup = window.open(winPath,winName,winFeature,true);
setTimeout( function() {
if(!popup || popup.outerHeight === 0) {
//First Checking Condition Works For IE & Firefox
//Second Checking Condition Works For Chrome
alert("Popup Blocker is enabled! Please add this site to your exception list.");
window.location.href = 'warning.html';
} else {
//Popup Blocker Is Disabled
window.open('','_self');
window.close();
}
}, 25);
Try Below..!!
var pop = window.open("about:blank", "new_window_123", "height=150,width=150");
// Detect pop blocker
setTimeout(function() {
if(!pop || pop.closed || pop.closed == "undefined" || pop == "undefined" || parseInt(pop.innerWidth) == 0 || pop.document.documentElement.clientWidth != 150 || pop.document.documentElement.clientHeight != 150){
pop && pop.close();
alert("Popups must be enabled.");
}else{
alert("Popups is enabled.");
pop && pop.close();
}}, 1000);
Look on below question
Detect blocked popup in Chrome
How do I detect whether popups are blocked in chrome
On Google It will more help you..
https://www.google.com/search?q=how+to+detect+a+blocked+popup+in+chrome
I found it much more effective to use try-catch as follows:
var popup = window.open(winPath,winName,winFeature,true);
try {
popup.focus();
} catch (e) {
alert('popup blocked!');
}
I know this is "resolved", but this simple code worked for me detecting "Better Popup Blocker" extension in Chrome:
if (!window.print) {
//display message to disable popup blocker
} else {
window.print();
}
}
Ockham's razor! Or am I missing something and it couldn't possibly be this simple?
I had used this method to open windows from js and not beeing blocked by Chrome.
http://en.nisi.ro/blog/development/javascript/open-new-window-window-open-seen-chrome-popup/
The below code works in chrome,safari and firefox. I have used jquery for this.
var popupWindow = window.open("http://www.google.com","directories=no,height=100,width=100");
$(document).ready(function(e) {
detectPopup();
function detectPopup() {
if(!popupWindow) {
alert("popup will be blocked");
} else {
alert("popup will be shown");
window.open('','_self');
window.close();
}
}
});

iPhone Javascript Confirm Dialog Bug

I have a javascript confirm dialog popping up, but when I tap 'Cancel', then after the dialog closes, tap anywhere on the screen, the dialog pops up again. It only happens the one extra time, then you can tap on the page again without the dialog popping up.
I'm only seeing this on iPhone/iPad running iOS 5.0.1. I don't have an iOS 6 device, so I'm not sure it's happening there.
Here's the code I'm using:
$(bpm.remoteAppDivName).on('tap', 'a.delete-pending-payment', function(event) {
if (isJQMGhostClick(event)) { return false; }
var deleteGlobalPaymentURL = $(this).attr('href');
var confirmMsg = confirm ("Are you sure you want to do that?");
if (confirmMsg === true){
window.location = '/index.htm';
}
event.preventDefault();
return false;
});
var lastclickpoint, curclickpoint;
var isJQMGhostClick = function(event){
curclickpoint = event.clientX+'x'+event.clientY;
var ret=false;
if (lastclickpoint === curclickpoint) {
ret=true;
} else {
ret=false;
}
lastclickpoint = curclickpoint;
return ret;
}
Here's a link to the problem page: http://www.5280skateparks.com/dev/confirmBug.htm
Any help would be extremely appreciated.
UPDATE: I just confirmed that it's happening on iOS 6.0.1 as well.
This is the jQuery Mobile "Ghost Click" discussed in some detail here and here. On the forum page, a solution was proposed, which I have reproduced below with a small bug fix:
var lastclickpoint, curclickpoint;
var isJQMGhostClick = function(event){
curclickpoint = event.clientX+'x'+event.clientY;
var ret=false;
if (lastclickpoint === curclickpoint) {
ret=true;
} else {
ret=false;
}
lastclickpoint = curclickpoint;
return ret;
}
I have modified this code slightly to not always expect a pair of clicks. This function now works correctly in the case of 0 ghost clicks and more than 2 ghost clicks. You can use it by checking isJQMGhostClick(event) at the beginning of your tap handler and ignoring the event if the isJQMGhostClick function returns true.

Categories