Search code examples
javascripthtmlmacossafari

How to turn off Safari opening previous page when using Command+Z?


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:

enter image description here enter image description here


Solution

  • 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);