java script+onbefore unload - javascript

i m creating a web application, after login user navigates to home page where i have a navbar(Links to pages/url).Navbar is like this
Home-Nvigates to home page
Profile-Navigates to profile page
Chat-navigates to chat page when user clicks on chat link .
I want that when user closes the browser window ,accidentally or manually he should get an alert for that i have used onbeforeunload function like this
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
Now when i m closing the browser on chat page i m getting following alert "You have attempted to leave this page." that is working fine,but now the main problem is that when i m clicking on other links like
Profile or Home this function is called and me geting this alert even though i have implemented this code in chat.jsp .Even i m refreshing this page i m getting this alert mentioned above which i should get only when i closes widow of chat.jsp page rather than other pages or Refresh.Plese help

Onbeforeunload fires when the page is unloading be it by refresh, navigate or page close. You could add an onclick eventhandler to anchors on your page that remove your onbeforeunload event to avoid it and you might be able to do the same with an onkeydown event on the window/body/page however I don't believe there's a way to catch users pressing the browser's refresh button.
example:
<html>
<head>
<script type="text/javascript">
function warnUnload(){
return "Your message here...";
}
function linkNavi(){
window.onbeforeunload = null;
}
function isRefresh(e){
var key = null;
if(window.event) // IE
key = e.keyCode;
else if(e.which) // Netscape/Firefox/Opera
key = e.which;
if(key == 116) //F5
window.onbeforeunload = null;
}
window.onbeforeunload = warnUnload;
window.onkeydown = isRefresh;
</script>
</head>
<body>
Google
Home
</body>
</html>

Related

windows onbeforeunload doesn't work Javascript

I want to prevent a close tab or close browser in a web page.
I am using this code:
<script type="text/javascript">
window.onbeforeunload = function(e) { //Doesn't work well
return 'Exit';
};
$('#form').submit(function() { //No alert on submit form (this works)
window.onbeforeunload = null;
});
</script>
If I click somewhere in the page the code works fine and ask me if I really want to close the page, but if I reload the page and then I close the tab without click something in the page the tab close without show any alert.
Do you have some idea how to fix?

How to detect closing and refreshing browser tab? [duplicate]

When we refresh the page (F5, or icon in browser), it will first
trigger ONUNLOAD event. When we close the browser (X on right top icon),It will
trigger ONUNLOAD event.
Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser.
If you have any solution then give me.
There is a solution.
I wanted to disconnect the user on the server when the tab or browser window was closed, but not when the page was reloaded (you may want to differentiate reload/close events for a different purpose but you may benefit from my solution). I ended up with the following process, based on HTML5's local storage and client/server AJAX communication:
on your page, add an onunload to the window to the following handler (pseudo-javascript):
function myUnload(event) {
if (window.localStorage) {
// flag the page as being unloading
window.localStorage['myUnloadEventFlag']=new Date().getTime();
}
// notify the server that we want to disconnect the user in a few seconds (I used 5 seconds)
askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call
}
on your page, add a onloadon the body to the following handler (pseudo-javascript):
function myLoad(event) {
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)) t0=0;
var t1=new Date().getTime();
var duration=t1-t0;
if (duration<10*1000) {
// less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
} else {
// last unload event was for a tab/window close => do whatever you want (I do nothing here)
}
}
}
on the server, collect the disconnection requests in a list and set a timer thread which inspects the list at regular intervals (I used every 20 seconds). Once a disconnection request timeout (i.e. the 5 seconds are gone), disconnect the user from the server. If a disconnection request cancelation is received in the meantime, the corresponding disconnection request is removed from the list, so that the user will not be disconnected.
This approach is also applicable if you want to differentiate between tab/window close event and followed links or submitted form . You just need to put the two event handlers on every page which contains links and forms and on every link/form landing page.
Note that I use the unload event instead of the beforeUnload event in order to manage links to attachments properly: when a user clicks on a link to an attachment (e.g. PDF file), the beforeUnload event is dispatched, then an open/save popup is raised, and nothing more (the browser does not change the displayed page and does not dispatch the unload event). If I were using the beforeUnload event (as I did before), I would have detected a page change when there is none.
This approach is limited to the browsers which support HTML5 local storage, so you would probably use specific approaches for old browsers such as MSIE7.
Other approaches based on the event.clientY are not reliable because this value is negative when clicking on the reload or tab/window close buttons, and positive when keyboard shortcuts are used to reload (e.g. F5, Ctrl-R, ...) and window closing (e.g. Alt-F4). Relying on the event X position is also not reliable because the buttons are not placed at the same position on every browser (e.g. close button at the left).
Maybe someone is still searching for an answer...
You can use SessionStorage for that! SessionStorage is not cleared when the page is reloaded but when it is closed. So basically you could set a key/value pair when the page is loaded, but before that you check if the key/value pair exists. If it does exists it means that the page was reloaded, if not it means that the user opened the page for the first time or in a new tab.
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes');
This way you can doStuff() with the onunload event (user leaves the page), and otherStuff() if the key/value pair is set (user reloaded the page).
Unfortunately inspecting the clientY/pageY value of the event, as suggested by some of the answers here, is not a reliable way to determine if the unload event is being fired by as a consequence of the user closing the page.
The reason clientY/pageY is negative when you click the browser's close button is because the close button is positioned above the top of the document (i.e. above pixel 0), but so is the reload button meaning that clicking the reload button will also result in a negative value for clientY/pageY.
Going down the path of inspecting the x co-ordinate of the event is also problematic because the browser close button is not always on the right hand side of the window (e.g. it's on the left in OS X) and because a window can be closed by closing its tab or via the keyboard.
This is a huge hack with some limitations but it will work in most practical cases.
So if you just need something that works when users use the ctrl+r or cmd+r shortcut, you can keep track of whether r is pressed when whatever you need to do upon reload/close gets run.
Simply create keydown and keyup event listeners that toggle a rDown variable.
let rDown = false;
window.addEventListener("keydown", event => {
if (event.key == 'r')
rDown = true;
})
window.addEventListener("keyup", event => {
if (event.key == 'r')
rDown = false;
})
Then you have your "onunload" event listener where the listener function has an if statement checking if rDown is true.
window.addEventListener("onunload", () => {
if (!rDown) {
// code that only gets run when the window is closed (or
// some psychopath reloads by actually clicking the icon)
}
});
Today I had the same problem and found a possible solution that I want to share with you.
While thinking about what could help to discern between refresh and close, cookies came to my mind. I remember that setting a cookie without an explicit expiration date, renders it available only for the current session. And a current session is clearly valid until the browser is closed. This does not include closing a tab, but my problem was about user authentication and I didn't want to logout the user only for having closed a tab (I think that's the same approach as the ASPXAUTH cookie of ASP.NET).
So, I put a simple cookie in the document.cookies collection when user logged in and checked it on page load: if cookie was still there it was a refresh or a reopened tab and user data was kept, if cookie was not present session had expired so user data was cleared (same as an explicit logout).
Hope this approach can be useful to someone else!
Unfortunately there is no suggested or reliable way yet.
Use the window.onbeforeunload event for the case to navigate away from page, but it will include refreshing or anchor tags .... use a validation flag for the same, 1 example for the process is the URL check(Initial URL = current URL) or F5 check using keycode for refresh, In case of anchor tags use the bind()
Note* Keycode may cause problem in case of Chrome.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script src="jquery-1.9.1.js" type='text/javascript'></script>
<script type='text/javascript'>
var valid=false;
function wireUpEvents() {
if(valid){
alert("Page Refreshed or Redirected");
}else{
window.onbeforeunload = askWhetherToClose;
}
function askWhetherToClose(event) {
if(!valid){
var msg;
msg = "You're leaving the page, do you really want to?";
event = event || window.event;
event.returnValue = msg;
return msg;
}}
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
// or you can insert some code to check page refresh
valid = true;
//wireUpEvents();
}
});
$("a").bind("click", function() {
//To check redirection using Anchor tags
valid = true;
//wireUpEvents();
});
}
$(document).ready(function() {
wireUpEvents();
});
</script>
</head>
<body>
<p>Close the browser window, or navigate to StackOverflow</p>
</body>
</html>
Credit to https://www.anandkanatt.com/how-do-i-detect-browser-window-closed-refreshed/#comment-15892. I simplified it a little by using the opener itself to check. Tested in Chrome Version 78.0.3887.7.
You may try this:
Add a refresh-close-detector.html file. Here's the sample code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Processing...</title>
</head>
<body>
<script>
if (this.opener) {
// the opener was refreshed, do something if you want
} else {
// the opener was closed, do something if you want
}
// you may want to close the pop up
this.close()
</script>
</body>
</html>
In the page you want to identifying between refresh and close browser actions, add an event listener to unload:
window.addEventListener('unload', () => {
open('refresh-close-detector.html', '', 'width=100,height=100');
})
I just tried this and it solved the issue:
Create a sessionStorage object which will get destroyed when the user closes the browser. We can check the sessionStorage object to find if the user has closed the browser or refreshed the page(sessionStorage object will not be destroyed on page refresh).
$(window).bind('unload', function () {
if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
console.log('firefox delete');
var data = { async: false };
endSession(data);
return null;
}
else {
console.log('NON-firefox delete');
var data = { async: true };
endSession(data);
return null;
}
});
function endSession(data) {
var id = 0
if (window) { // closeed
id=1
}
$.ajax({
url: '/api/commonAPI/'+id+'?Action=ForceEndSession',
type: "get",
data: {},
async: data.async,
success: function () {
console.log('Forced End Session');
}
});
}
Use if (window) to determines if closed or just reload. working for me.
Its a working solution
export class BootstrapComponent implements OnInit {
validNavigation = 0;
constructor(
private auth: AuthenticationService
) { }
ngOnInit() {
const self = this;
self.registerDOMEvents();
}
registerDOMEvents() {
const self = this;
window.addEventListener('unload', () => {
if (self.validNavigation === 0) {
self.endSession();
}
});
document.addEventListener('keydown', (e) => {
const key = e.which || e.keyCode;
if (key === 116) {
self.validNavigation = 1;
}
});
}
endSession() {
const self = this;
self.auth.clearStorage();
}
}
My earlier solution worked for me in IE. window.event would be undefined for browsers other than IE as 'event' is globally defined in IE unlike in other browsers. You would need to supply event as a parameter in case of other browsers. Also that clientX is not defined for firefox, we should use pageX.
Try something like this....should work for IE and firefox this...
<html>
<body>
<script type="text/javascript">
window.onunload = function(e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;
if(y < 0) alert("Window closed");
else alert("Window refreshed");
}
</script>
</body>
</html>
<html>
<body onunload="doUnload()">
<script>
function doUnload(){
if (window.event.clientX < 0 && window.event.clientY < 0){
alert("Window closed");
}
else{
alert("Window refreshed");
}
}
</script>
</body>
</html>

JavaScript code not working in Firefox for ASPX web site

I have the following JS code that helps signing out a session from an ASPX page so a 'log out' record can be stored in a database. The code works when the site is opened with IE11, EDGE, and Chrome. Using those three browsers the user gets the popup asking if staying on the site or leaving the site. When it comes to be tested in Firefox, at least version 54, it just does not work. Nothings pops up.
Code is:
//We want to capture when a user logs out from the system - this is a way to force the browser to log out the session
window.onbeforeunload = closingCode;
function closingCode() {
// when user clicks the 'X' from the browser, will be prompted to leave or to stay
//clicking any of the options will trigger an event that will capture when the session was logged out and saved in the db
var button = document.getElementById('btnLogout');
button.click();
return "You are closing or refreshing this site. Clicking 'Stay on this page' will log out your session. Clicking 'Leave this page' will close your window.";
//return null;
}
//this will prevent the popup to appear everytime user navigates between pages/links
$(document).ready(function () {
$('a[rel!=ext]').click(function () {
window.onbeforeunload = null;
});
$('form').submit(function () {
window.onbeforeunload = null;
});
});

javascript open window url on exit

Hello I am trying to open a new URL on page exit in a browser window using javacript. My goal is when user closes the window to see the javascript alert box and when he press "Leave this Page" Instead ot the browser window to be closed to be redirected to google.com.
my code so far is the following:
<script type="text/javascript">
$(document).ready(function(){
var areYouReallySure = false;
var internalLink = false;
function areYouSure() {
if (!areYouReallySure && !internalLink) {
areYouReallySure = true;
location.href="http://www.google.com"
return "Do you wish to go to google?";
}
}
window.onbeforeunload = areYouSure;
$('a').click(function(){
internalLink = true;
});
});
</script>
Rigth now when I chose leave this page it only closes the window.
This is impossible, and with good reason. Imagine if spam sites controlled what happens when you close their page. As a security measure, the only thing you can do when a user tries to navigate away from your page is display a message. This was implemented mostly so users can be warned that they haven't saved their data.

Page exit via hyperlink not being catched by onberforeunload

I have an onberforeunload method which is correctly alerting the user when they are trying to close the tab or the browser using the follwoing code:
window.onbeforeunload = function(event) {
event.returnValue = 'Are you sure you want to leave/';
console.log(event.returnValue);
};
I have discovered that the onberforeunload is not being called when I click a hyperlink on the page. The warning message I want to display isn't appearing and the page is loading freely.
I have searched for many ways to create a popup for when a hyperlink has been selected but they all deal with one or groups of hyperlinks in div tags. I wish for a popup to display if any hyperlink is selected.
Why isn't onbeforeunload catching the exiting of the page through a hyperlink? Is my understanding of onbeforeunload wrong that it should be catching hyperlink exits?
UPDATE
I have updated the code to the following:
window.onbeforeunload = closeIT;
function closeIT() {
return 'here';
if(searchOnGoing){
return 'Ifs you leave the Youtube History page now the application will not finish';
}
};
It is still not working for hyperlinks and working for browser and tab closure. I am running this as part of a content script in a chrome extension which is injecting the content script into the page. Would this have an effect on it?
I also have an onunload following,i am wondering would this also have an effect on it?
window.onunload = function(event){
//Do something
}
Actually, it should trigger. Do you catch the event somehow via a click-event-listener? Anyway, you could show an alert with help of a click-event listener.
Following code-snippet is copied from a similar question: how to detect if a link was clicked when window.onbeforeunload is triggered?
Here the question was, in contrast, how to prevent the beforeunload event when links are clicked.
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function() {
if(link_was_clicked) {
link_was_clicked = false;
return;
}
//other code here
}
The following snippet correctly uses onbeforeunload.
<body onbeforeunload="return myFunction()">
Click me!
<script>
function myFunction() {
return "Please don't go!\nThis works beautifully!";
}
</script>

Categories