How to access JavaScript href event that triggered beforeunload - javascript

I would like to access the event that caused a beforeunload event. Specifically, if I click on a link to another page, I would like to know what the link was in the beforeunload event handler.
In this way, I would be perform different actions in the beforeunload event handler according to what the URL was.
Eg 'http:' or 'https:' warn user about losing unsaved changes; 'mailto:' or 'skype:' don't warn user because page is not actually going to be unloaded.
I am trying to build a good solution to a problem like this:
mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?

I was all prepared to tell you this was impossible because the onbeforeunload event only reports to have been triggered by the window when you check out event.target, event.originaltarget, etc. If you override window.onclick, however, we can modify that method to register which element was last clicked on the page. Then, by providing code for window.onbeforeunload, we can specify new behavior that will check for the href of the element which was clicked last. Hooray, beer!
Here's code that will give you exactly the information you want though, in pure javascript and with no cruft to add inside your anchor tags. I've also thrown in the preventDefault() which will pop up the "This page is asking you to confirm that you want to leave - data you have entered may not be saved." confirm box. Hope this helps - you can figure out what to do from here.
<!DOCTYPE html>
<html lang="en">
<head>
<title>12065389</title>
<meta charset="utf-8">
<script type="text/javascript">
var last_clicked;
window.onclick = function(e) {
last_clicked = e.target;
return true;
}
window.onbeforeunload = function(e) {
var e = e || window.event;
if (last_clicked.href) {
alert(last_clicked.href);
e.preventDefault();
}
}
</script>
</head>
<body>
google
</body>
</html>

I would probably attach the event to all links on the page, rather than the beforeunload event.
Something like:
$("a").click(function(evt) {
if($(this).attr('href').indexOf('http') == 0) {
if(confirm("Are you sure?")) {
//continue
} else {
evt.preventDefault();
}
}
}

Related

First click is being ignored after page load

This webpage has a simple event listener, when I right click it blocks opening the context menu. simple enough.
But when I refresh the page or on initial load of the page, if I start with right mouse clicking the page, it shows the context menu, then blocks it ever time I right mouse click after that. I tried it in Chrome, FireFox and IE. Same results.
I experience the same thing with mouse down, keydown, or touch events, etc. It is like the first click is ignored. I am looking for JavaScript solution (not jquery). What am I missing?
<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function () {
window.addEventListener("contextmenu", mouseright);
}
function mouseright() {
document.oncontextmenu = function(e) {
var e = e || window.event;
alert("right");
e.preventDefault();
}
}
</script>
</head>
<body>
hello world
</body>
</html>
I even tried adding this before the event listener (as in this post keydown not detected until window is clicked), had no luck with document.onload and did see that it could be a possible browser focus on page load setting. Any thoughts or other ideas I didn't try in JavaScript?
if (document.hasFocus() == true) {
} else {
window.focus();
}
You're unnecessarily assigning the event twice (as both window.contextmenu and document.oncontextmenu). Removing the extra wrapper seems to work:
window.onload = function () {
window.addEventListener("contextmenu", mouseright);
}
function mouseright(e) {
var e = e || window.event;
alert("right");
e.preventDefault();
}
(The window.onload may also be unneeded, depending on where you place the addEventListener in the document.)

How can I detect browser tab refresh or close using javascript [duplicate]

This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 7 years ago.
I have one problem, I have a javascript function which I want to use when the browser is closed, How can I detect that a browser is being closed?
I have made some research on that I got solution like onunload or beforeunload but both the functions are being executed when I am reloading the page, Is there any solution that I can differentiate reload and browser/tab close.
No, you can't know that, the HTML page isn't the "owner" of the browser, you have only limited access to information, and this info isn't inside it.
You can know when the user leaves your page, but you can't know why, as it's none of your business...
gdoron is correct in that you cannot determine why/how the user is 'leaving the page'.
On the extremes you can perhaps determine on mousedown events if the browser's CLOSE button was clicked and let that fire of an alert.
But this would probably require tracking the X and Y of the mousedown event and that isn't a very nice way of doing things. And i do not think you would be able to accurately determine if a tab is closed.
answer is,
</head>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
</head>
<body>
<h1>Eureka!</h1>
Google
Yahoo
</body>
</html>

Preventing site from refreshing using JS

Some websites have the annoying quality of auto-refreshing using some JS magic. This seems to bypass the browser's "do not auto refresh" options.
My question - is there a simple way of telling the browser (also via JS, in an add-on) "do not listen to them! Never auto-refresh!"?
EDIT: Just to make myself clear - I want to write a browser extension that prevents the current page from giving a "refresh" signal - whether auto-refresh or "standard" refresh given automatically by the page using some timer. I think that's a standard JS question...
Edit: Sorry, I missunderstood the question!
I think that what you need is this:
window.onkeypress = window.onkeyup = window.onkeydown = function( event ) {
event.preventDefault();
// or, in this case:
//return false;
};
When the window will receive the events of keypress, keyup e keydown signals that the default behavior MUST be prevented. If you return false, you will stop the event chain, preventing to execute anything too. The two lines have the same effect, give a try commenting each line.
Here is a improoved example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing...</title>
</head>
<body>
<div id="clickDiv">Click me ;)</div>
<br/>
<input id="typeInput" value="Type something ! (here)"/>
</body>
<script type="text/javascript">
window.onkeypress = window.onkeyup = window.onkeydown = function( event ) {
event.preventDefault();
return false;
};
document.getElementById( "clickDiv" ).onclick = function( event ) {
console.log( "you clicked me and the window events related to the keyboard are still being prevented ;)" );
};
document.getElementById( "typeInput" ).onkeyup = function( event ) {
console.log( "you typed inside me and the window events related to the keyboard are still being prevented ;)" );
};
</script>
</html>
All popular browsers except Chrome and Safari already have options related to disabling auto-refreshing. To disable auto-refreshing in these browsers, check out this article: http://maketecheasier.com/disable-web-page-auto-refresh-for-various-browsers/2010/12/12
For a Chrome extension to stopping auto-refresh, check this out: https://chrome.google.com/webstore/detail/lcldcllmbokpbniijpnkpgoboadbfphb
Each browser can have this functionality turned off but I don't think there is a way to affect these changes through JS unless you write an "Extension".

how to identify onbeforeunload was caused by clicking close button

How do I determine if onbeforeunload was caused by clicking the close button or a page refresh or generally what event caused onbeforeunload?
here is a snippet:
window.onbeforeunload = function( e ){
if( !e ) e = window.event;
// insert code to determine which is the source of the event
}
Please help me.
Referring to various articles and doing some trial and errors, finally developed this idea which works perfectly for me just the way i wanted it to happen. The logic was quiet simpler it implement as well The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the Close('X') button.
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
The ConfirmLeave function will give the pop up default message, it case there is any need to customize the message, return the text to be displayed instead of empty string
See if this helps, :)
As far as I know, there is no way of determining what caused the onbeforeunload. The event is triggered when window is about to close whether closing the browser or some other way.
If the close button was pressed the value of e.clientY is negative. For the other possible sources i doubt there is a solution.
window.onbeforeunload = function() {
var e = window.event;
alert(e.clientX + " / " + e.clientY);
}
I searched for something similar but ended up empty handed.
So I tried doing the opposit
We can identify all the events but browser events.
Refer below (Untested) snippet.
var target = $( e.target );
if(!target.is("a, :button, :submit, :input, .btn, .bulkFormButton")){
//Your code for browser events)
}
$("form").submit(function () {
//Your code for browser events)
});
This worked for me but there are still some events that are not handled.
I am in search of those.
If anyone have idea about them please share.

How to prevent the user to change page with jQuery

I have a page with a form that is submittes via ajaxSubmit() (so, without changing the page).
My goal is that, when the user try to change page (or even to close the browser), i ask him if really want to exit the page without sending the form (exactly as gmail does).
Gmail for example do this with a window.confirm-like popup, but if it is possible, i'll like to handle it with custom messages and options.
jQuery have the unload event:
$(window).unload( function () { alert("Bye now!"); } );
but it permits me just to do something before exit the page; i need to 'block' the page exit, if the user click the relative button.
So, how to handle (and cancel) the page-exit event?
try the following. Demo here
<script type="text/javascript">
function unloadPage(){
return "dont leave me this way";
}
window.onbeforeunload = unloadPage;
</script>
It's possible bind the "onbeforeunload" event with jQuery:
$(window).bind('beforeunload', function(e) {
return "ATTENZIONE!!";
});
It works!!

Categories

Resources