18
$(window).on("keydown", function (e) {
    alert(e.keyCode);
});

W has 87 key code. I also know that e.ctrlKey is true if Ctrl is pressed in that moment.

Is possible to catch the Ctrl + W key press and prevent tab closing?

I tried:

$(window).on("keydown", function (e) {
    if (e.keyCode === 87 && e.ctrlKey) {
        return false;
    }
});

But it seems that browser shortcut has priority in this case and the tab is closed.

I am searching for a solution: if it's not possible via JavaScript, maybe a browser add-on can do this.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Maybe `e.which` instead of `e.keyCode`? – xmarston Feb 11 '14 at 07:41
  • I don't think it is a good design to restrict users from leaving your page. – hjpotter92 Feb 11 '14 at 07:42
  • 1
    I can't comment, sorry) [Prevent closing discussion][1] [Another discussion][2] [1]: http://security.stackexchange.com/questions/46270/site-preventing-user-from-closing-tab-closing-browser [2]: http://stackoverflow.com/questions/3950981/closing-popup-window-created-by-google-chrome-extension – Farkhat Mikhalko Feb 11 '14 at 07:46
  • 3
    @hjpotter92 It's just for me: I run a terminal in browser and I often press `CTRL + W` to delete the last word, but the tab is closed... – Ionică Bizău Feb 11 '14 at 07:54

5 Answers5

12

This is a response not to the original asker, but to anyone who finds this question via search. This post is designed to give you the information and arguments you need to return to your boss or your client and tell them why this design is not able to be realized. The beforeunload solution is provided by the top answer to this question. Good luck getting them on-board!


The design in this project stipulates that some javascript code should prevent the user from closing a web page, without providing the user with a dialog box. There is one key problem with this: this is something which malicious websites also try to do. Web browser developers work to prevent malicious websites from taking over the user experience. For that reason, there is no good way to do this. Even if we find a solution, that solution will not be future-proof, and will break without warning coinciding with a browser update.

Web browser developers provide exactly one solution to us for preventing the close of the websites. That solution is called "the beforeunload solution". The beforeunload solution will give the user a dialog box, and the text in that dialog box will have standardized, boilerplate text with a "stay" button and a "leave" button. We can add some text to that dialog box, but we cannot remove the boilerplate text and we cannot change, move or otherwise manipulate the buttons. The beforeunload solution is inflexible, but it is future-proof.

Using a non-standard solution (otherwise known as a hack) to circumvent what beforeunload provides will thrust us into the arms-race between malicious websites and the web browser developers, and we will not be able to guarantee that our website's features will work consistently from day-to-day. Malicious websites often find new tricks and hacks to keep intrusive advertisements on-screen, so even if we find something which is allowed one day it might be banned the next. The internet is littered with no-longer-working non-standard solutions which web browser developers have shut down!

The beforeunload solution is the only workable solution in the long-term, and we will need to accept that the end-user can close our website for any reason, using any standard keyboard shortcut, and the only way we can prevent this is a dialog box which requests that they stay on the site.

Narpas
  • 261
  • 4
  • 7
  • 1
    It's really a problem when you press CTRL-W by accident, some people wanted to press CTRL-Z (in enlgish keyboard W is near Z) or CTRL-X (in french keyboard W is near X) but if they press CTRL-W, they lost all there work without any alert box ... Its the reason why some people want to capture CTRL-W to prevent the user to quit or to stay, all software do this, but it's impossible to do this alert in navigator only because you have hacker on internet ? You can use beforeunload for other reason than capturing CTRL-W, in this case you can not check if this exit was fired by CTRL-W – tomboul Aug 10 '20 at 10:37
  • It's also a problem when you're trying to make an in-browser VIM editor and people can't use C-w to backspace by a word in insert mode without closing the editor. – James M. Lay Jan 10 '21 at 02:53
4

You can avoid tab closing using 'beforeunload' event

$(window).on('beforeunload', function(e) {
    if(hasUnsaved()) {
        return 'You have unsaved stuff. Are you sure you want to leave?';
    }
});

See: http://hackab.it/2013/05/page-closing-confirm/

Sean Kendle
  • 3,538
  • 1
  • 27
  • 34
guzmanfg
  • 69
  • 1
  • 5
  • 2
    I already know this method, but I don't want to display any alert... I want just to prevent the tab close using `CTRL + W`. – Ionică Bizău Feb 12 '14 at 07:04
1

Especially in firefox it's annoying, that CTRL+W can't really be turned off. Even if you plan it solely for your personal use, where changes in your config or your settings could possibly do the job.

However, you can use as a workaround the "beforeunload" event in javascript. Make sure to have the third parameter (useCapture) set to true, in order to intercept the keystrokes before they are picked up by anything else.

Here's the code:

addEventListener(
    'beforeunload',
    function(e){
        e.stopPropagation();e.preventDefault();return false;
    },
    true
);
Wayne
  • 11
  • 2
0

Try this code:

$(window).keypress(function(event) {
            event.preventDefault();

            if (event.which == 119 && event.ctrlKey) {
                alert("Ctrl-W pressed");
            }    

    return false;
});
Rakesh Kumar
  • 2,705
  • 1
  • 19
  • 33
0

I know it's probably irrelevant for your scenario, but I found the CTRL+SHIFT+W shortcut (close all windows) extremely annoying when you are just closing a load of tabs with CTRL-W and using CTRL-TAB to move between them. You sometimes accidentally hold down the shift key and then Chrome exits when you just meant to do CTRL-W.

So for Windows (not sure if you meant Linux, but you can do the same thing there with xbindkeys):

  1. Install https://www.autohotkey.com
  2. To disable the ^+W short cut on windows, add this into AutoHotkey.ahk:

(Apologies: if the following doesn't show up in "code" format)

^+w::
SetTitleMatchMode RegEx
IfWinExist, Google Chrome$
{
    WinActivate
}
return

Hopefully this will be useful for someone looking for a way to stop Chrome even getting the CTRL-SHIFT-W key combo.

Malcolm Boekhoff
  • 1,032
  • 11
  • 9
  • Thanks! Hmm, I do like the CTRL + W shortcut and I use it to close the tabs. I just want to disable it on a specific page. :) – Ionică Bizău Jan 24 '18 at 08:57