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.
Related
Script
window.addEventListener('popstate', function (event) {
console.log(core.current.queryString.k);
if (!core.current.queryString.k || core.current.queryString.k == "") {
$(".container").removeClass("some-class");
$(".container-class").css("height", "");
$(".container-class").css("bottom", "50px");
isSearchBarInputted = false;
}
});
The popstate event is skipped upon hitting the back browser button. It works fine before but I guess the recent updates on Chrome affected this. Are there any ways to remediate this? I'm just starting to get familiar with javascript.
Thanks in advance!
I have a Javascript function with following code.
function NodeClickActions(sender, eventArgs) {
event.preventDefault();
//Get whether user clicked CTRL key or not
var bCtrlPressed = eventArgs.get_browserEvent().ctrlKey;
//URL of the actions page
var URL = "../Actions.aspx";
//If CTRL key was pressed
if (bCtrlPressed) {
parent.MainPage.location.href = URL + "?PackageId=00000000-0000-0000-0000-000000000000&All=" + bCtrlPressed;
}
else {
parent.MainPage.location.href = URL;
}
}
I need to stop the page being opened in a new tab. Please note, event.PreventDefault(); won't do the trick unfortunately.
I understand this is due to browser behaviour rather than the code.
Any suggestion is welcome. Regards!
Here is the most simpliest way for that, preventing click on url is much smarter then preventing pressing of CTRL/CMD buttons because functionality like CTRL/CMD + CLICK is browser functionality and cannot be overwritten (or at least I didn't have success with it)...
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
window.location.href = $(this).attr("href");
});
});
depend on case where you will use you need to apply something similar for form submiting... because that is also affected with this browser functionality
Important: OS X users using Command + Click, never forget that
Addition:
Because you want to disable open in new tab/window functionality under binding "click" just do preventDefaults for contextmenu (right mouse button)
$("a").contextmenu(function(e){
e.preventDefault();
});
Detect key of ctrl press or not .Use Jquery For event handling easly
var ctrl=false;
$(document).on('keydown',function(e){
console.log(e.ctrlKey)
}).on('click','a[href]',function(e){
if(!ctrl){
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
one
You need to add listener directly on anchor tag instead of using event delegation and adding on parent element. Working example here.
HTML
Click Me
JS:
$(document).ready(function ()
{
$("a").on('click',function(event)
{debugger;
event = event || window.event;
event.preventDefault();
event.stopPropagation();
return false;
});
});
I'm trying to implement a popup (bootstrap modal style) that would be triggered as web visitor leaves my site.
I tried different alternatives of:
$(window).bind('beforeunload', function(){
$("#sModal").modal('show');
return 'Take our survey before you leave.';
});
However, it didn't work in FF while worked fine in IE. I had another problem also, that the "Do you want to leave or stay" alert was being displayed on any link click on my website itself, across all browser types, as the whole page was being loaded.
I got around this by looping through all my anchor tags and adding a click listener to remove the beforeunload listener using:
window.onload = function () {
var allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
allLinks[i].addEventListener("click", removeBeforeUnload, false);
}
};
The removeBeforeUnload function just used the
$(window).unbind('beforeunload');
Getting back to actually make the popoup/modal appear on all browsers, i used the code from this stackoverflow answer after my document completes loading:
window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?
This solution works great across all browsers, however now I cannot unbind this event on any of my local clicked links! I tried everything
window.removeEventlistener('beforeunload',null,false);
window.removeEventlistener('onbeforeunload',null,false);
window.removeBeforeUnload();
window.onbeforeunload = null;
I hope you can point me in the right direction and explain why I cannot unbind this event, that I used from stackoverflow answer.Thanks!
One thought is use a global variable flag and don't do anything in the unload event handler when flag isn't truthy. Set this flag to null or false in link click handlers
Then you don't really need to remove the listener
var doUnload = true;
$('a').click(function(){
doUnload = false;
});
function unloadhandler(){
if(doUnload){
// show modal , return message etc
}else{
// do nothing , don't return anything
}
}
Probably jQuery is adding a 2nd beforeunload event listener, which you can't remove via the DOM API the same way as the one added to the Window by default.
What should work for you is:
var allLinks = $('a');
for (var i = 0; i < allLinks.length; i++) {
$(allLinks[i]).on('click', () => {
$(window).off('beforeunload');
// now add any custom code you want for handling this event
$("#sModal").modal('show');
)};
}
Is there a way to capture to result of the window.onbeforeunload confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?
This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.
Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?
I've implemented this like below:
// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}
// pseudo code
listen to changes on inputs
if any inputs fire a change event
call setConfirmUnload(true, 'My warning message')
note I'm using jQuery within my site.
I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete flag) then sending them on their way.
My question also relates to:
jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?
You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.
To quote an earlier response from jvenema from this thread:
The primary purpose for the
beforeunload is for things like
allowing the users the option to save
changes before their changes are lost.
Besides, if your users are leaving,
it's already too late [...]
How about this:
$( window ).bind( 'beforeunload' , function( event ) {
setTimeout( function() {
alert( 'Hi againe!' );
} );
return '';
} ).bind( 'unload', function( event ) {
alert( 'Goodby!' );
} );
Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.
public listenToUnloadEvents(): void {
window.addEventListener('beforeunload', (e) => {
const confirmationMessage = '\o/';
(e || window.event).returnValue = confirmationMessage; // Gecko + IE
return confirmationMessage; // Webkit, Safari, Chrome etc.
});
window.addEventListener('unload', () => {
this.sendNotification(Action.LEFT)
});
}
I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.
As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel
window.addEventListener('focus', (e) => {
if (didEnterBeforeUnload) {
console.log('pressed cancel')
}
didEnterBeforeUnload = false
});
As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.
I hope this helps anyone else out there!
I have this:
function dontMove(event) {
// Prevent page from elastic scrolling
event.preventDefault();
}
&
<body ontouchmove="dontMove(event);">
This, on the ipad, stops it from being draggable and does not allow that grey background the ipad has when you drag a whole page around to show up.
I have seen on another website that its possible to reverse that in another div, so that div is completely draggable again.
Does anyone know how to reverse it?
I have also tried using this to prevent it (in the document.ready):
document.ontouchmove = function(e){
e.preventDefault();
}
& this to enable it:
function doTouchMove(state) {
document.ontouchmove = function(e){
return state;
}
}
Then I put this to activate it.
<img ontouchmove="doTouchMove(state);" src="../jpeg/pages/01.jpg" class="touch"/>
This didn't seem to work
Is there anything wrong with this?
Or any other way that might work?
This is exactly why bubbles is slightly better(at least in my opinion).
bubbles is cross browser, so you should be able to replace.
e.preventDefault()
with
e.bubbles = false;
and then latter in your code, you could potentially reset bubbles to true.
If the above isn't an option then just ignore. :D
An alternative(if you are just working with an iPad) is to just reverse how the DOM works.
document.addEventListener('click', function(){}, true );
This will force the event to work in the other direction.
Document click execute
|
|
v
Element click execute
try this post, HTML with event.preventDefault and erase ontouchmove from body tag.
Mine looks like this
<script>
// Get touch move enevt from IOS
document.ontouchmove = function (event) {
if (!event.elementIsEnabled)
event.preventDefault();
};
// Get touch move enevt from IOS
function enableOnTouchMove(event) {
event.elementIsEnabled = true;
};
</script>
then enable ontouchmove on every tag you want. ie:
<div ontouchmove="enableOnTouchMove(event)" id="listing">
I managed to solve it with
$('#form1').unbind('submit').submit();
You can solve it by preventing the event only if it comes from the body:
document.ontouchmove = function(event){
if(event.target.tagName == "BODY"){
event.preventDefault();
}
}