Does Safari handle the paste event correctly?

前端 未结 2 1027
梦谈多话
梦谈多话 2021-01-04 14:21

I\'m trying to write some code for Safari for handling the \'paste\' event, but it doesn\'t seem to work right. According to the WebKit DOM reference, oncut, <

相关标签:
2条回答
  • 2021-01-04 14:50

    Don't know if it helps you, but I use a out-of-screen input to force safari accept paste on the page. It helped me so here it goes:

    I'm doing:

    script:

    $(document).bind('paste', function(e) {
        var data = e.originalEvent.clipboardData.getData('Text');
        // here using data from clipboard
    });
    
    $(function(){
       $('input.special').focus();
    });
    

    css:

    input.special{
    position:absolute;
    top:-40px;
    }
    

    html:

    <input type="text" class="special" style="position: absolute;top:-40px;">
    
    0 讨论(0)
  • 2021-01-04 15:08

    I think the answer, as unsatisfying as it might be, is "no". See this WebKit bug:

    https://bugs.webkit.org/show_bug.cgi?id=75891

    If your intention is to receive paste data into something that's not contentEditable, a text input or a text area, I don't know of any method to make the current version of Safari do this.

    Update: an attempted work-around in this JSFiddle, simplified to only deal with text, does not work in Safari 6.0.5. It attempts a work-around where a hidden text field is automatically focused when Cmd-V is pressed, just in order to enable pasting in Safari. It does prevent the "you can't paste beep", but no paste event is sent and nothing is pasted into the secret input.

    $(function () {
        $(window).bind('keydown', function (e) {
            // Cmd-V
            if (e.which == 86 && e.metaKey) {
                if (e.target.nodeName.toUpperCase() !== "INPUT")
                    $('#secretinput').focus();
            }
        });
    
        $(window).bind('beforepaste', function (e) {
            return false;
        });
    
        $(window).bind('paste', function (e) {
            var clipboardData = e.originalEvent.clipboardData;
            console.log(clipboardData);
            $('#textdest').html(clipboardData.getData('text/plain'));
        });
    });
    
    0 讨论(0)
提交回复
热议问题