Display warning alert and close session when the browser is closed - javascript

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;
}

Related

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

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>

On close tab ask for unsaved changes and then reload the page - How?

I've come across a nasty website that managed to refresh the page every time I tried to close the tab. Basically you couldn't close that page. I got around it by disabling javascript on that page.
How do they do it?
I've tried location.replace inside onbeforeunload and it doesn't work:
window.onbeforeunload = function(e) {
window.location.replace(window.location.href);
};
Here is the source of the page in question, where I don't get how they do it:
<script type="text/javascript">
function c(b)
{
document.write(b);
}
function wrapped3(d)
{
return d.replace(/(.)(.)/g, '%$1$2');
}
function wrapped(b)
{
var tmp = window['decodeURI' + 'Component'];
return tmp(wrapped3(b))
}
function show_page(a)
{
c(wrapped(a)
.split('{{addr}}').join('//ip')
.split('{{country}}').join('Great Britain')
.split('{{region}}').join('London, City of')
.split('{{city}}').join('London')
.split('{{ltude}}').join('//latitude')
.split('{{referrer}}').join('//url here')
);
}
show_page('//long string here');
</script>
window.onbeforeunload is the correct solution, here is an example:
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
http://jsfiddle.net/SQAmG/3/

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.

Add a javascript alert when a user tries to close the current tab in browser

I am working on asp.net(c#).I try to add a javascript alert when a user tries to close the current tab in browser. The code is not working in Chrome.Please can any one help about this topic.
This is my code:
<script type="text/javascript">
window.onbeforeunload = function close_window() {
var r = confirm("Do you want to view other topics?");
if (r == true)
{
alert("You pressed OK!");
var Url = "http://stackoverflow.com/";
window.location = Url;
return false;
}
else
{
window.close();
}
}
Remove the () when you're calling the function.
It should be:
window.onbeforeunload = function close_window {
Actually, try this.
function close_window() {
...
}
window.onbeforeunload = close_window;
And yes--it's really bad practice.

Categories

Resources