Hi we are facing the problem with escape key in our web application. If user press the escape key the web application gets stop loading.
I tried using all these with(onkeydown and onkeyup)
document.attachEvent("onkeydown", win_onkeydown_handler);
window.attachEvent("onkeydown", win_onkeydown_handler);
window.document.attachEvent("onkeydown", win_onkeydown_handler);
I cant able detect the escape(KeyCode=27) in my web application .. but i am able to detect refresh,f5 and all other keys
Note: i face this problem in IE
This helps me to prevent escape in iframe
function disableEscapeAndRefresh(){
try{
if(window.frames && window.frames[0]){
window.frames[0].focus();
for (var i_tem = 0; i_tem < window.frames.length; i_tem++){
if(document.all && document.body.filters)
window.frames[i_tem].document.onkeydown = new Function("var e=window.frames["+i_tem+"].event; if(e.keyCode==116){e.keyCode=0;alert('Refresh Not Allowed');return false;}if(e.keyCode==27){e.keyCode=0;alert('Escape Not Allowed');return false;};");
}
}
}catch(e){
}
}
call this method in iframe onload
I don't think there's any way to trap that... it's the equivalent of clicking the X to stop the page loading.
Assuming that you are targeting versions of IE that have attachEvent enabled, you can use this to detect the escape key being pressed. The handling of the event is the usual code for preventing default event behaviour, though this may not work on cancelling the page download as this may be seen as a security flaw (imagine the unscrupulous developer that wants to prevent the user from cancelling a malicious download):
document.attachEvent('onkeydown', function(){
if(window.event.keyCode == 27) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
});
http://jsfiddle.net/steveukx/LJHs8/
Related
I've noticed recently in Safari, in some cases, if I press Command+z that it will open the previously opened browser tab.
It's messing up my web application. Sometimes it correctly performs Undo and others it is opening the previous page (when there is no more undo history). Is this a bug or is it a feature I can turn off in JavaScript or HTML? My application does not always have the cursor inside a text field so I need to prevent Safari taking the event.
This is Mac OSX 10.11, Safari 10.1.
Safari changing from Undo Typing to Undo Close Tab:
While it looks like this might be worth reading, I'd recommend against this practice and instead look into the way your application is built. Re-opening a previously closed tab is a common action people perform in the web browser and your application should be able to handle this.
I added a listener to the window object for the keypress event and called preventDefault() on the event:
function preventDefaultWindowOpen(prevent) {
var isSafari;
var useCapture = true;
const KEYTYPE = "keypress";
if (navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
navigator.userAgent && !navigator.userAgent.match('CriOS')) {
isSafari = true;
}
else {
return true;
}
if (window.preventOpenOnUndoKey==null) {
window.preventOpenOnUndoKey = function(event) {
if (event.keyCode==122 && event.metaKey==true) {
event.preventDefault();
}
}
}
if (prevent) {
window.addEventListener(KEYTYPE, window.preventOpenOnUndoKey, useCapture);
}
else {
window.removeEventListener(KEYTYPE, window.preventOpenOnUndoKey, useCapture);
}
return true;
}
preventDefaultWindowOpen(true);
I am trying to create, essentially, a 'kiosk'
I have an web application that I want to be the only thing accessible on screen. I know chrome has a 'kiosk' mode (shortcut: chrome.exe --kiosk www.url.com). That takes care of the auto-fullscreen, but disables very few shortcuts (perhaps only f11).
With a bit of help from the internet, I wrote out some javascript that gets most of the job done. The code is as follows:
window.onload = function() {
window.document.body.onkeydown = function() {
if (event.ctrlKey) {
event.stopPropagation();
event.preventDefault();
try {
event.keyCode = 0; // this is a hack to capture ctrl+f ctrl+p etc
}
catch (event) {
}
return false;
}
return true; // for keys that weren't shortcuts (e.g. no ctrl) then the event is bubbled
}
}
This takes care of things like ctrl+f, ctrl+p, etc. Unfortunately, it does not disable shortcuts such at ctrl+t, ctrl+n, f5, etc.
Is it even possible to disable these, or am I chasing a rainbow here? I don't care if it's javascript, settings, whatever, but I would really like to do it without a plugin.
You can disable any keys you want via javascript. You just need to know the key code for them.
Rather vague title, I know, but I'm binding a custom key event to the document object to catch AltR combination keypresses, like this:
document.body.onkeydown = function(event){
event = event || window.event;
var keycode = event.charCode || event.keyCode;
if (keycode === 82) {
if (event.altKey) {
if (!canReload) {
canReload = true;
window.location.href += "#doGreaseRefresh";
} else {
canReload = false;
window.location.href = window.location.href.replace("#doGreaseRefresh", "");
}
return false;
}
}
}
The code runs as expected but also produces a rather annoying "beep" sound as well. How can I prevent this? return false didn't prove to be the answer, so I'm wondering if it's even possible.
Oh, and if you're wondering, this is in a Chrome userscript (Content script) to refresh Stack Overflow's home page every 10 seconds if I've pressed AltR, and to stop refreshing once I've pressed AltR again. :)
Not being able to stop the beep is apparently a bug in Chrome: http://code.google.com/p/chromium/issues/detail?id=105500. return false works in Firefox without a beep.
Cheers-
As ZachB points out, this appears to be a bug with Chrome.
To work around this annoyance:
Go into the Windows control panel.
Select Sounds or System Sounds
Assign (None) for the sound of the Default Beep.
(I like to do this anyway, since it's 50 times more annoying than it is useful).
How to prevent a webpage from navigating away using JavaScript?
Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:
window.onbeforeunload = function() {
return "";
}
Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.
In older browsers you could specify the message to display in the prompt:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.
Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.
(function () {
var location = window.document.location;
var preventNavigation = function () {
var originalHashValue = location.hash;
window.setTimeout(function () {
location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
location.hash = originalHashValue;
}, 0);
};
window.addEventListener('beforeunload', preventNavigation, false);
window.addEventListener('unload', preventNavigation, false);
})();
Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
In Ayman's example by returning false you prevent the browser window/tab from closing.
window.onunload = function () {
alert('You are trying to leave.');
return false;
}
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
JSFiddle example
altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.
That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.
In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).
A more appropriate error message might be:
window.onbeforeunload = function() {
return "If you leave this page, you will lose any unsaved changes.";
}
Or stackoverflow style: "You have started writing or editing a post."
If you are catching a browser back/forward button and don't want to navigate away, you can use:
window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});
Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});
If you need to toggle the state back to no notification on exit, use the following line:
window.onbeforeunload = null;
I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work - I cannot seem to bind to the beforeunload event.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
Angular 9 approach:
constructor() {
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
if (this.generatedBarcodeIndex) {
event.preventDefault(); // for Firefox
event.returnValue = ''; // for Chrome
return '';
}
return false;
});
}
Browsers support and the removal of the custom message:
Chrome removed support for the custom message in ver 51 min
Opera removed support for the custom message in ver 38 min
Firefox removed support for the custom message in ver 44.0 min
Safari removed support for the custom message in ver 9.1 min
Try placing a return; instead of a message.. this is working most browsers for me.
(This only really prevents dialog's presents)
window.onbeforeunload = function(evt) {
//Your Extra Code
return;
}
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :
1) It was giving message on all navigations I want it only for close click.
2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
refer from http://www.codeprojectdownload.com
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Try this
$(window).bind('beforeunload', function (event) {
setTimeout(function () {
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
alert("User wants to continue!");
return true;
}
else {
window.stop();
return false;
}
});
return;
});