onbeforeunload keeps poping up an alert box when user click something - javascript

I am created a page that warns the user when they click on the (close x) button on the window. I did some reading and discovered that JavaScript had a function called onbeforeonload which can take of the job I was trying to achieve. I however found at after my implementation that, when a user clicks on anything in my window (example: save and enter) The dialog box reappears. I was wondering how I could only target the specific X button in the window.
window.onbeforeunload = function (evt) {
var message = 'Do you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}

Right now the function is being called globally... this resource might help you achieve what you are looking for: http://randomdrake.com/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/

This is a "working as intended" behavior for IE. Anchor tag clicks, regardless of whether they navigate or not, will trigger the onbeforeunload event.
This is the workaround I used - I am not sure whether it is the best approach or not:
document.onmouseup = function () {
if (window.event.srcElement.tagName === 'A') {
// turn off your onbeforeunload handler
...
// some small time later, turn it back on
setTimeout(..., 200);
}
};

Related

How can I catch the click outside the browser - Javascript

For my project, I need to catch all the click outside the browser in Javascript. Is there a way to do that ? For example by asking the user the right access ?
I need a function like "onclick" that works even outside the browser.
There are various approaches for detecting when the focus moves out of the current page which would be a side effect of clicking outside the window if the window currently has focus.
Explicitly detecting clicks outside the page is not possible. It would be a security problem if a web page could monitor how the user interacts with other applications.
To detect click outside element with JavaScript, we can use the element’s contains method.
For instance, we write
const specifiedElement = document.getElementById("a");
document.addEventListener("click", (event) => {
const isClickInside = specifiedElement.contains(event.target);
if (!isClickInside) {
// ...
}
});
to select the element we want to check with getElemebntById.
Then we add a click listener for the whole page with document.addEventListener.
In the callback, we call specifiedElement.contains with event.target to check if we clicked inside the a element.
If it’s false, then we clicked outside of it.
javascript detect click outside of element
var ignoreClickOnMeElement = document.getElementById('someElementID');
document.addEventListener('click', function(event) {
var isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
if (!isClickInsideElement) {
//Do something click is outside specified element
}
});
click outside javascript
// Vanilla js
var ignoreMe = document.getElementById("ignoreMe");
window.addEventListener('mouseup', function(event){
if (event.target != ignoreMe && event.target.parentNode != ignoreMe){
// Place your output
}
});
https://www.codegrepper.com/code-examples/javascript/javascript+detect+click+outside+of+element

How to prevent navigation by browser buttons but not by links?

I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the “Are you sure you want to navigate away from this page?” when changes committed? this may solve your problem How

Exit confirmation in Javascript with Telerik controls

I'm using Telerik controls for my project. On my page, there are some links to another page, several radtextboxes and a radbutton (it causes a postback). When the textbox values are changed, the button becomes enabled. Then, in my window.onbeforeunload, I check if the button is enabled or disabled. If it is enabled, then the confirm dialog appears. The code looks like this :
window.onbeforeunload = function (evt) {
var ClientGeneral_btnSave = $find('<%=btnSave.ClientID %>');
if (ClientGeneral_btnSave.get_enabled() == true) {
var message = 'You will lose unsaved data?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
This code works well. When I close the tab, the confirm dialog appears. When I click on the links, it does. But, when I click on the btnSave itself, the dialog appears too, which is unsual. I want the btnSave NOT to cause onbeforeunload event
Please tell me how to do this.
Thank you in advance
It will fire onbeforeunload this if the btnSave posts back which it looks as if it is. Therefore you have a couple of choices
Prevent the btnSave from posting back if you don't need it to. Easiest way to do it is put this attribute in the asp:Button markup
OnClientClick="return false"
Wire up a javaScript/jQuery method to disable the onbeforeunload event. I did this before by stashing an value in a hidden field and using this to signal that the onbeforeunload event should fire.
for instance
$('#<%= btnSave.ClientID %>').bind('click', function(e){
$('#myHiddenFieldId').val('1');
});
and change your on beforeunload handler to check that the hidden field is not equal to 1 (make 0 the default i.e.
window.onbeforeunload = function (evt) {
if( $('#myHiddenFieldId').val() != '1')
{
//your logic here
}
}
You could probably do something better by unbinding the onbeforeunload handler in the btnSave click event using JQuery rather than using a hidden field to override.
Option 2 can get fiddly though - so best of luck

I want to call function on window unload

I am trying to display confirmation box using window.confirm on window unload event.
If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.
My code is:
<script>
function confirmit(){
var result=window.confirm("Are you sure?");
if(result) {
// close all child windows
} else{
// window should not get close
}
}
</script>
<body onunload='confirmit();' >
But the problem is if I click on CANCEL button, window is getting closed.
Please help me.
You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)
<script type="text/javascript">
window.onbeforeunload = function(e){
var msg = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = msg;
return msg;
}
</script>
More info here
JSFiddle Example here
change your code to this to make it work cross-browser:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Do you really want to exit?';
}
// For Safari
return 'Do you really want to exit?';
};
</script>
<body>
...
note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.
i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "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?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories