Javascript, controlling an onbeforeunload tag - javascript

I'm trying to set up a onbeforeunload tag to stop a user from leaving specific pages if and only if they have unsaved content, and only on specific pages (we're using a single master page). I quickly discovered that having a return ##anything## in the onbeforeunload tag would always trigger a javascript confirm, and puts ##anything## inside the pop-up. Obviously, this is now expected behavior, but it does take away my idea of using my own confirm box that could be controlled with an if statement.
I tried this, and it didn't work:
<body class="yui-skin-sam" onbeforeunload="document.onFormClose();">
<script>
document.onFormClose = function () {
if (document.getElementById('DirtyFlag').value == "true") {
document.getElementById('DirtyFlag').value == "false";
return 'You will lose all changes made since your last save';
}
}
</script>
where DirtyFlag is a hidden field that turns true if any unsaved changes exist. I'd hoped that putting the return inside the function would do the trick, but no such luck.
So my question is, is there a way to use the onbeforeunload tag with a return built in that will bypass it pending the value of that field?
Alternatively, (though this would be less ideal) I suppose I could add or remove the onbeforeunload tag dynamically, in all the places I set or reset the getElementById tag. Unfortunately, I don't know how to do that either.
Oh, and I'm restricted completely from using jQuery or any other javascript library.

Not sure if this is as designed, but if you return null from the event handler, you might get the results you want:
window.onbeforeunload = function() {
var el = document.getElementById("dirtyFlag");
if (el.value === "true") {
return 'You will lose all changes made since your last save';
}
else {
return null;
}
};
The following works in FF: http://jsfiddle.net/andrewwhitaker/chZJ8/. Try changing the hidden inputs value to "true" and you should start getting the confirmation dialog. However, I cannot get it to work in Chrome and I'm unable to test in IE. It would be great if someone could confirm this works in either of those browsers.
Edit: Adding another example that's easier to use and works in Chrome (the iFrame in JSFiddle was causing issues). Check out the example here: http://andrewawhitaker.com/examples/onbeforeunload_test.html. Type 'true' in the input to see a confirmation. If 'true' is not the value of the input, no dialog is displayed. Works in FF and Chrome, still can't vouch for IE.
Update 2: A more reliable way of doing this is probably to add and remove the event listener when you set the value for dirtyFlag programmatically, just remove or add the event handler appropriately:
var isDirty = function() { ... };
if (/* form is dirty*/) {
window.onbeforeunload = isDirty;
}
else {
window.onbeforeunload = null;
}

You can't change the default behavior of onbeforeunload.
https://developer.mozilla.org/en/DOM/window.onbeforeunload
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

Related

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

How to 'disable are you sure you want to navigate away from this page' in post-new , have tried MANY solutions of onbeforeunload

Hey I'm making a custom backend for Wordpress, it's a bit 'ghetto' but it turned out to be bigger than expected so I'm running with it. Works perfectly fine stylistically and functionally but for some reason if I submit a new post with it, I get "Are you sure you want to navigate away from this page?" or whichever browser equivalent.
I've tried a shitton of variations of onbeforeunload = null, returning blank functions, etc, none of the solutions have worked on any browser, so I assume it's something to do with Wordpress backend constantly updating...?, I read that it might be a factor that you can't bind onbeforeunload like a normal event as well, so a combination of these two makes me wonder, how can I permanently silence "are you sure" notices on a page, no questions asked?
It seems everywhere on the web is a variation of this question and/or setting the onbeforeunload null worked for them, it does not in any sense for me, even in inline JS onthe form. I have no idea why it's even triggering, I assume I moved something when reconstructing the WP submit form that causes it to ungroup data... or something, but I just need to silence all dialog from this page that is "save changes", that's all, seems like it's easy enough with a bind/event handler but they haven't worked and I don't quite get how the event works.
I've tried this and some other binds thus far, as well as putting return onbeforeunload null function inline the form
window.onbeforeunload = function() {
return null;
}
window.onbeforeunload = null;
jQuery('a, input').click(function(){
window.onbeforeunload = null;
});
If the events were registered using jquery with $(window).on('beforeunload' you can remove them using $(window).off('beforeunload'
This example demonstrates the click event, but it works the same with the beforeunload event:
$(function() {
$(window).on('click', function() {
alert(1);
});
$(window).on('click', function() {
alert(2);
});
$(window).off('click')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Disable IE back Button

I have a application where i have disabled the back button of IE8 by using the following code.
window.history.forward();
function noBack() {
window.history.forward();
}
I know this code takes the page back and again moves the page forward. i have called a function onload of the page which makes a textbox read only. i have used the following code to make it read only.
$("#IDofTheTextBox").attr('readonly',true);
but if i select the textbox and try to edit by pressing "BackSpace" button, IE back button is getting invoked and the textbox which was readonly is not readonly anymore. Can anyone help me how to solve this issue?
The answer is simply "NO"
If you're trying to prevent the user from losing their work, try something like:
window.onbeforeunload = function() { return "Are you sure want to leave this page?."; };
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
You add the above javascript functions in the js file and onload call the function changeHashOnLoad().
its working fine in IE8. i just tested it.
I dont know what your page is trying to do... but this is what we do:
We have an assessment where we do not want the browser buttons enabled... because we run ajax/logic when the user hits next/back etc (to determine what to display next based on their inputs). Back and forward buttons can muddy that process up.
So..... we have users open our assessments in A NEW WINDOW so the back button is already disabled...(there is no prior history in a new window). Then, Our next/back buttons use window.location.replace(url); This will prevent a history item from being created. Therefore, the back/forward buttons are never enabled and they must use the next/prev buttons to navigate our tool.
I would not try to muck with the buttons outside of something like the example I provided.

Javascript function fails to perform task in Google Chrome

I've been researching this problem for a while, and given the immense amount of issues Google Chrome seems to have with Javascript, I've been having trouble finding anyone with this same issue.
The problem is this: when the anchor calls a new function which replaces the contents of a div, it shows the proper result for a moment before reverting to the default contents of the div prior to any changes by Javascript.
Here's the script:
function prologueThree() {
document.getElementById('content').innerHTML = document.getElementById('prologue3').innerHTML;
}
function prologueFour() {
userName = document.getElementById('yourname').value;
if(userName.length === 0) {
alert("Erm... are you sure that\'s your name?");
prologueThree();
} else {
document.getElementById('content').innerHTML = '<center> \
<img src="http://pokemonroleplay.thedevhome.net/images/Gameboy/characters/red.png"><br> \
Right, so your name is ' + userName + '! \
<br><br> \
<a onclick="prologueFive()"><button>>>Continue>></button></a></center>';
}
}
This is only a snippet of the script, but the entire thing works fine in Firefox and for the first three prologue functions it works fine in Chrome. It's only when it tries to run prologueFour that it freaks out and go back. I've also tried the Chrome developer console, but it never registers an error.
Thank you in advance for your help.
I went to your site
and I noticed you are binding an onclick to a submit button in your form without preventing the default behavior from executing, the default behavior being a form submission which refreshes the page and thus makes you lose your place and go back to the beginning. Use a plain old button or anchor tag like you do for your previous prologues. If you insist on using a submit for whatever reason, prevent the default behavior like so:
function prologueFour(e) {
typeof e.preventDefault === 'function'
? e.preventDefault()
: e.returnValue = false;
// now rest of code can continue without page refresh
}
I don't know if there are other issues, but >>Continue>> isn't exactly standards-compliant html, which could be causing problems. You should use > instead.

Silverlight 4: OnBeforeUnload

I have a silverlight application and I want to capture the close event of the browser. So what I did, in my .aspx page i have this code
function closeIt() {
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
If this functions triggered, a popupwindow will appear, you have 2 buttons OK and CANCEL.
Is there a way in silverlight or in server side to get the value of what the user clicks?
Thank you
I am not sure I totally understand your question, it looks like you are writing javascript. But your subject is silverlight. Anyway....
The simplest way is to leverage Html Confirm either in silverlight:
bool result = System.Windows.Browser.HtmlPage.Window.Confirm("Really..?");
or in straight JavaScript:
var result = window.Confirm("Really...?");
To get the value to the server you can store the value in a hidden text field and post it to the server.
Why don't you use MessageBox ? here's code example:
MessageBoxResult result = MessageBox.Show("Text","Title",MessageBoxButton.OKCancel);
if (MessageBoxResult.OK==result)
{
}
else if (result == MessageBoxResult.No)
{
}
this will get you a popup window with OK and CANCEL window with pretty easy way to determine whether user clicked Ok or no.
The answer is pretty much the same as my other answer to your prior question re window.close.
When the user selects Cancel absolutely nothing happens. If they select OK then your Application_Exit will run.

Categories

Resources