How to activate onbeforeunload after window.location reloads the page? - javascript

I use onbeforeunload in my project. However there is a section where user can click on the link and download report(s). Before window.location is being triggered I set window.onbeforeunload = null that way user won't be getting alert/confirm box with the question to leave or stay. There is a problem once they click on report and download the file if they try to close the browser onbeforeunload is not triggered again. How I can trigger onbeforeunload after report is downloaded? Here is example of my function:
function getReport(){
var fileName = $(this).prop('id'),
param = 'rptFile=' + fileName;
try{
window.onbeforeunload = null;
window.location = '/'+pathname+'/APPS/entry.cfm?idx=5&' + param;
}catch(err){
alert("An error occurred retrieving the file.");
}
};
My main page that I'm reloading entry.cfm has document.ready function where I have onbeforeunload function. I expected once report is downloaded with window.location then onbeforeunload will br triggered again. So I'm not sure if I'm doing something wrong or this is not possible with JS. Here is entry.cfm example:
$(document).ready(function() {
window.onbeforeunload = function () {
return 'Are you sure you want to leave?';
}
});
If anyone knows how to trigger onbeforeunload again please let me know. Thank you!

This will work, do not null window.onbeforeunload just replace your window.location with window.open to open report in new tab.
function getReport() {
try {
window.open('https://via.placeholder.com/350x150/ee5533', '_blank');
} catch (err) {
alert("An error occurred retrieving the file.");
}
};
window.onbeforeunload = function() {
return 'Are you sure you want to leave?';
}
$('.dwl').on('click', getReport );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="dwl">Try to download in new tab</a>

Related

Avoid onbeforeunload in location.href

I have the code below which asks for confirmation when a user tries to reload the page. It works fine
window.onbeforeunload = function(event) {
return confirm('Confirm refresh');
};
In another part of the code, I am redirecting it to the page using window.location.href It returns a popup whether you want to leave the page. How can I avoid this popup when using window.location.href?
window.location.href = window.location.href.split('#')[0];
You could just set a variable to skip this behaviour :
let skipUnloadConfirm = false;
window.onbeforeunload = function(event) {
if(!skipUnloadConfirm) {
return confirm('Confirm refresh');
}
};
And then change value before setting href (function would replace direct window.location.href assignement and could be reused)
function redirect(url) {
skipUnloadConfirm = true;
window.location.href = url;
}
Or, you can override window.onbeforeunload before calling redirect

How can i handle page refresh event in React.js

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave.
but issue is that when user refresh page using browser refresh btn in google chrome that time below error occur
I tired this code but doesn't work in react.js please help
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!window.hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});
Also try this code
window.onbeforeunload = function () { return ''; }.bind(this);
Try this code it's work for me
window.onbeforeunload = function () {
if ("Some condition") {
return '';
}
}.bind(this);
you can also use that
winodow.location.reload(true)
winodow.location.reload(false)
Please use this:
console.log(window.performance.navigation)

Display warning alert and close session when the browser is closed

The web page is displayed upon redirection from another website and the URL changes during this process to point to a different port number.
So, I would like the JavaScript to detect if the URL is correct.
If the user closes the browser/tab, display an Alert Box with warning message.
Run PHP script to close the user Session
My code is:
if (window.location.href === "http://abc123.net.au:2048 ") {
$(function () {
try {
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}
catch (e) {
}
function OnBeforeUnload() {
$(window).onbeforeunload;
// Post to script that will log the user out
xmlhttp.open("POST", "../logscript.php", true);
xmlhttp.send();
}
function ReturnMessage() {
return "Wait, by closing this session I will end your session. You will be required to log in again t access the site.";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload', ReturnMessage);
});
}
else {
document.write('<div>code is not working</div>')
}
This is the solution to your second work order:
window.onbeforeunload = bunload;
function bunload() {
dontleave = "Are you sure you want to leave?";
return dontleave;
}

onbeforeunload function having serious issue

I am using native.history.js to put a customised URL in the back button.
The script works fine. Now the issue is I want to make a page redirect when the refresh button is clicked; so i modified the script like this:
<script>
var back = 0;
$(window).bind('beforeunload', function () {
if (confirm('Want to continue?')) {
if (back == 1) {
alert('back');
//window.location.href = "<?=$$last_offer?>";
} else {
alert('refresh');
//window.location.href = "<?=$actual_link;?>";
}
} else {
// Do nothing!
}
});
window.onpageshow = function (e) {
if (e.persisted) {
location.reload();
}
};
window.onpopstate = function (event) {
if (document.location.toString().indexOf("redir=1") > 0) {
back = 1;
window.location.href = "<?=$$last_offer?>";
}
};
</script>
Issue is, the beforeunload function seems not working.
What is the problem I can't fin?.
If I am clicking the back button, the page is taking to the desired page, so it works fine.
All I want is that, somehow the page refresh must work as I anticipated.
Try use
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Instead of bind, use on, i dont know what jquery version you use, but i will suggest "on".
Works fine here:
link
on jquery version 2.x(edge)

using onbeforeunload event, url change on selecting stay on this page

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

Categories

Resources