admin管理员组

文章数量:1323335

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:

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:

Share Improve this question edited Mar 28, 2017 at 8:13 1.21 gigawatts asked Mar 28, 2017 at 7:35 1.21 gigawatts1.21 gigawatts 17.9k40 gold badges143 silver badges272 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

This is exactly right: "Safari is stealing the undo keyboard event from my web page."

That's what's happening. Safari steals the CMD-Z from your keyboard that'd normally be sent into Google Docs.

While it looks like this might be worth reading, I'd remend against this practice and instead look into the way your application is built. Re-opening a previously closed tab is a mon 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);

本文标签: javascriptHow to turn off Safari opening previous page when using CommandZStack Overflow