Confirmation Before Closing of Tab/Browser

Confirmation before closing of tab/browser

Try this:

<script>
window.onbeforeunload = function (e) {
e = e || window.event;

// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}

// For Safari
return 'Sure?';
};
</script>

Here is a working jsFiddle

Ask for confirm when closing a tab

You need to listen on the beforeunload event.

Here's a kickoff example:

window.onbeforeunload = function() {
return "Hey, you're leaving the site. Bye!";
};

This message will show up in kind of a confirmation dialogue. This message will show up right before the client unloads the page. That can be a browser close, but that can also be a simple navigational action like clicking a link or submitting a form in the page!

You would most probably also like to turn it off (just set to null) whenever an internal link is clicked or an internal form is submitted. You namely don't want to annoy endusers with unintuitive behaviour. You can do that by listening on the click event of the desired links and the submit event of the desired forms. jQuery may be of great help here since it does that in crossbrowsercompatible way so that you don't need to write >20 lines of JS code for this:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
</script>

You only need to give all external links the defacto standard attribute rel="ext" to denote that those are external links.

<a href="http://google.com" rel="ext">Google</a>

Confirmation Box on closing browser in React

You can use window.onbeforeunload function, to show a popup before closing the browser window.

Eg: Inside the componentDidMount of your component, write the following code:

window.onbeforeunload = function(e) {
if( //queue not empty ) {
return;
}
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};

This is not in anyway related to React, but just a function provided by the window object. Also check browser compatibility

Confirm box before closing a tab

I assume that on page load, you are setting up var sncro=1; and when some data changes, you adjust this value. Here is the quick check:

window.onbeforeunload = function (evt) {
if (sncro != 1) {
var message = 'Are you sure you want to leave, cause there are some unsaved changes?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt ) {
evt.returnValue = message;
}
return message;
}
}


Related Topics



Leave a reply



Submit