document.executeCommand('paste') 在 chrome 中不起作用

document.executeCommand('paste') not working in chrome

本文关键字:chrome 不起作用 executeCommand document paste      更新时间:2023-09-26

我在我的网站中添加了一个鼠标右上下文菜单,其中包含功能(剪切,复制,粘贴)。我使用了document.executeCommand()。剪切和复制可以工作。但是粘贴在 Chrome 中不起作用(它在 IE 中工作)。我该如何解决这个问题。

是的,这不起作用。 但一切都没有丢失。 可以从粘贴事件捕获剪贴板的内容。

我在这里写过:http://blog.dmbcllc.com/cross-browser-javascript-copy-and-paste/

这里有一个github:https://github.com/DaveMBush/CrossBrowserCopyAndPaste

这都是直接的JavaScript,适用于IE,FF和Chrome(我已经测试过)

(function () {
var systemPasteReady = false;
var systemPasteContent;
function copy(target) {
    // standard way of copying
    var textArea = document.createElement('textarea');
    textArea.setAttribute('style','width:1px;border:0;opacity:0;');
    document.body.appendChild(textArea);
    textArea.value = target.innerHTML;
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
}
var textArea;
function paste(target) {
    if (window.clipboardData) {
        target.innerText = window.clipboardData.getData('Text');
        return;
    }
    function waitForPaste() {
        if (!systemPasteReady) {
            setTimeout(waitForPaste, 250);
            return;
        }
        target.innerHTML = systemPasteContent;
        systemPasteReady = false;
        document.body.removeChild(textArea);
        textArea = null;
    }
    // FireFox requires at least one editable 
    // element on the screen for the paste event to fire
    textArea = document.createElement('textarea');
    textArea.setAttribute('style', 'width:1px;border:0;opacity:0;');
    document.body.appendChild(textArea);
    textArea.select();
    waitForPaste();
}

function systemPasteListener(evt) {
    systemPasteContent = evt.clipboardData.getData('text/plain');
    systemPasteReady = true;
    evt.preventDefault();
}
function keyBoardListener(evt) {
    if (evt.ctrlKey) {
        switch(evt.keyCode) {
            case 67: // c
                copy(evt.target);
                break;
            case 86: // v
                paste(evt.target);
                break;
        }
    }
}

window.addEventListener('paste',systemPasteListener);
document.getElementById('element1').addEventListener('keydown', keyBoardListener);
document.getElementById('element2').addEventListener('keydown', keyBoardListener);
})();