I want to build a JS external script ( tag) which stops code (which usually isn't mine) like location.href from happening without the use of a popup.
I tried things like:
$(window).bind('beforeunload', function() {
window.stop();
event.stopImmediatePropagation();
event.preventDefault();
location.href = '#';
});
but nothing seemed to help.
again, I need it without the use of the: return "are you sure?"
maybe a different callback?
Thanks,
Dan
The right way to use onbeforeunload to confirm navigating away is to just return the string of the message you want to have shown. MDN has this to say.
The function should assign a string value to the returnValue property of the Event object and return the same string
So your onbeforeunload function for the behavior you ask for would just be (same as binding it with jquery, especially since onbeforeunload does not support multiple event listeners like other events do)
window.onbeforeunload = function() {
return "Are you sure?";
};
But ironically, Firefox doesn't support this for security purposes.
Note that in Firefox 4 and later the returned string is not displayed to the user. See bug 588292.
Edit: I read more of the bug report. The main reason they site for this decision is: "1. Remove the site-supplied text, since this is a security issue (untrusted text in browser dialogs)". I wonder how they feel about an alert?
Most modern browsers (Chome, IE 9+ or earlier, and Opera, I know for sure) will ignore anything you try to do in an onbeforeunload function other than returning a string for display. This is to prevent hijacking the users browser, opening popups, overriding navigation attempts by pointing the user another, possibly malicious domain, etc.
Edit 2: I was apparently incorrect. Only some things are disallowed in onbeforeunload, they just happen to mainly be the types of things you tried in your sample code, having to do with event propagation and page navigation. From deep in the comments of that FF bug report, user oyasumi posts a link to this jsFiddle with a work around for displaying custom text to FF 4+ users: http://jsfiddle.net/ecmanaut/hQ3AQ/ So apparently calling alert() is still allowed, even in onbeforeunload, which hilariously is doing exactly what the was original reason for the 'bug' "fix": displaying custom text in a browser/application/OS/official-looking dialog.
did you try to use "return false" ?
Also you should have the event sent to your function.
here is an example where you can prevent from a button click and hyper link
<input type="button" value="click me" />
google
$(document).ready(function(){
$('input[type="button"]').click(function(e){
e.preventDefault();
});
$('a').click(function(e){
e.preventDefault();
});
});
here is the link http://jsfiddle.net/juTtG/143/
Related
When the user closes the tab or refreshes the page, the site must display a popup to confirm this.
I tried this code:
window.onbeforeunload = function (e) {
return confirm("Are you sure you want to leave this page?");
};
This didn't work in either firefox or chrome.
In firefox no popup came up. And in chrome the default one didn't get overridden either.
I even tried using the following code but to no avail:
window.onbeforeunload = function (e) {
var dialogText = 'Are you sure about this?';
e.returnValue = dialogText;
return dialogText;
};
How do I solve this issue?
Any code snippets would be helpful. Thank you.
I found this snippet on the internet:
window.onbeforeunload = function (e) {
return "Please click 'Stay on this Page' if you did this unintentionally";
};
This is working perfectly as required.
I found out that you actually don't need to add any confirm call. If you just return a string, this will prompt the browser to confirm leaving the page. Most commercial browsers have this functionality supported by default.
From Firefox's documentation:
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with.
You cannot show pop-up if user didn't interacted with the page before.
Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."
-- from Mozilla Developer Docs
I have a form where the input fields are saved onChange. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn't and I need to be sure that I'm saving this data even if they try to close the window after they've typed in a field but an onBlur event hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).
I have read the following SO articles on using window.onbeforeunload:
article 1
article 2
if I use the following:
window.onbeforeunload = function() {
return "onbeforeunload";
}
then I get a popup with onbeforeunload in.
but if I try:
window.onbeforeunload = function() {
alert("onbeforeunload");
}
then nothing happens in any browser, even Firefox.
what I want to achieve is:
window.onbeforeunload = function() {
saveFormData();
}
I'd be grateful if someone could point out where I might be going wrong.
You have to return from the onbeforeunload:
window.onbeforeunload = function() {
saveFormData();
return null;
}
function saveFormData() {
console.log('saved');
}
UPDATE
as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)
FROM MDN
Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.
It is also suggested to use this through the addEventListener interface:
You can and should handle this event through window.addEventListener() and the beforeunload event.
The updated code will now look like this:
window.addEventListener("beforeunload", function (e) {
saveFormData();
(e || window.event).returnValue = null;
return null;
});
There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).
The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).
Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).
In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.
An example of how I use it (pseudo code):
onbeforeunload = function() {
if(Application.hasUnsavedChanges()) {
return 'You have unsaved changes. Please save them before leaving this page';
}
};
If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.
The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."
But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:
"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"
That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:
window.addEventListener
('beforeunload'
, function (evt)
{ evt.preventDefault();
evt.returnValue = 'Hello';
return "hello 2222"
}
);
If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.
But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.
So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.
Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.
SEE:
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:
window.onbeforeunload = function() {
return false;
};
I placed this as an inline script immediately after my Head and Meta elements, like this:
<script>
window.onbeforeunload = function() {
return false;
}
</script>
This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunload and window.onbeforeunload):
https://javascript.info/onload-ondomcontentloaded
Hoping this helps.
you just cant do alert() in onbeforeunload, anything else works
To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
Yes what everybody says above.
For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.
Is it possible to trigger a javascript event when a user prints a page?
I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the library is great for screen but not for print.
Any idea how to achieve this?
For anyone stumbling upon this answer from Google, let me try to clear things up:
As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job.
However, as pointed out in Joe's link (https://stackoverflow.com/a/9920784/578667), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).
For more information (and browser support) for these two events:
https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint
https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint
The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.
It can be done by overwriting, e.g., window.onbeforeprint.
Using Chrome, I found that the more arcane window.matchMedia("print").addListener(function() {alert("Print Dialog open.")}) also works.
This debatable feature can be used in order to deter users from printing a page.
I've encountered it the first time on Scribd. There, if you open the print dialog using the menu command, the page content will be greyed out and a warning pop-over message appears explaining why you can not print the page. (Note for complete analysis: on that page, control-p is also overriden so you can not use it to open the print dialog at all. Additionally, there is a #media CSS for printer output that hides the content; all tested on Firefox).
I have implemented for disabling printing using window.onbeforeprint()
/*Block printing*/
window.onbeforeprint = (event) => {
console.log("onbeforeprint function");
printDiabled();
};
function printDiabled() {
var headstr = " <span style='font-size: large; font - weight: bold; color: Red''>PRINT IS DISABLED</span>";
//var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr;
}
/*Block printing*/
if you have a scenario where u want to do something before print dialog appears or just after the document is sent to printer queue use can use the below events
window.onafterprint , window.onbeforeprint
For anyone coming here looking for an option using Bootstrap as I was, I used the following code to achieve this when a print button is clicked. This won't work when they press CTRL + P.
$("#print_page").click(function(){
$("#print_section").addClass('visible-print-block');
window.print();
$("#print_section").removeClass('visible-print-block');})
You need to add hidden-print to anything you don't want printed and then add an ID (or a class if you have more than one section) of print_section to the bit you want printed! Bit hacky but it works!
I have written this code
function winUnload() {
alert("Unload Window");
MyMethod();
}
window.onunload = function() { winUnload(); }
This code is working fine in IE and Firefox. But this code is not working in Chrome. Both the statements alert("Unload Window"); and MyMethod(); are not working.
There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.
But what is possible (AFAIK):
Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.
Example for #2:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
Demo: http://jsfiddle.net/PQz5k/
I know this is old but I found the way to make unload work using Chrome
window.onbeforeunload = function () {
myFunction();
};
Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.
But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:
window.addEvent("beforeunload", function() {
return "Are you sure you want to leave this page?";
});
So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
}
Not sure why this is the case, or if it's been fixed in later versions of Mootools.
You may try to use pagehide event for Chrome and Safari.
Check these links:
How to detect browser support for pageShow and pageHide?
http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
Please try window.onbeforeunload instead for window.onunload for chrome.
You can also try calling onbeforeunload from the body> tag which might work in chrome.
However, we do have a problem with unload function in chrome browser.
please check
location.href does not work in chrome when called through the body/window unload event
The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.
The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.
This works :
var unloadEvent = function (e) {
var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
};
window.addEventListener("beforeunload", unloadEvent);
I would like to ask a question about window.onbeforeunload.
I consider making a covering-element appear before confirming whether to unload or not.
But the following code seems not to work fine. The dom element 'COVERALL' appears just after confirming unloading.
window.onbeforeunload = function(event){
$( COVERALL )
.css('zIndex', 1000000)
.fadeTo(1000, 1.0);
~~~~
~~~~
some time-consuming tasks here
~~~~
~~~~
return event.returnValue = "are you sure?";
}
The correct way to do this is using an event listener to capture the event object and then prevent the default action which is to leave.
window.addEventListener('beforeunload',
function(e)
{
if (!confirm('Are you sure that you want to leave?'))
e.preventDefault();
}, 1);
Its implementation may vary between browsers though. In my Fiefox 6, it asks again to confirm once the e.preventDefault(); instruction is reached, as a security measure implemented by Mozilla.
August 1st:
Today I have tried, and, in Chromium browser, if you prevent default action without asking user for confirmation such as with a confirm box, the page will close anyways.
I did some research today about this, and I have found that it is apparently impossible to trigger a page close event from Javascript, so using a custom HTML made confirm box for this would be out. I tried creating custom events, dispatching them to various window elements and even inspecting and copying browser made events. (All this on Firefox, in Chromium I did not check because, well, no support in Firefox means not to ever rely on something like that)
But good news for you, I have found that if you quickly set up an XMLHttpRequest and send the information you want to save before leaving, the data sending will finish in background even if the page has been closed.
I have successfully been able to achieve that for both browsers with the following code.
window.addEventListener('beforeunload',
function(e)
{
var fd = new FormData();
fd.append('html', document.body.innerHTML);
var xhr = new XMLHttpRequest;
xhr.open('POST', './dataRetriever.php');
xhr.send(fd);
// uncomment these if you want confirmation for all browsers
// because this code will not ask for confirmation in others
// than Mozilla powered ones.
//if (!confirm('Leave?'))
// e.preventDefault();
}
, 1);
With that one, I send all the body innerHTML to my dataRetriever.php script so tell me how it goes and if it works for you as expected.