JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2411
小蘑菇
小蘑菇 2020-11-21 11:22

How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove HTML content before the text is pasted into a rich text edi

20条回答
  •  时光取名叫无心
    2020-11-21 12:01

    Based on l2aelba anwser. This was tested on FF, Safari, Chrome, IE (8,9,10 and 11)

        $("#editText").on("paste", function (e) {
            e.preventDefault();
    
            var text;
            var clp = (e.originalEvent || e).clipboardData;
            if (clp === undefined || clp === null) {
                text = window.clipboardData.getData("text") || "";
                if (text !== "") {
                    if (window.getSelection) {
                        var newNode = document.createElement("span");
                        newNode.innerHTML = text;
                        window.getSelection().getRangeAt(0).insertNode(newNode);
                    } else {
                        document.selection.createRange().pasteHTML(text);
                    }
                }
            } else {
                text = clp.getData('text/plain') || "";
                if (text !== "") {
                    document.execCommand('insertText', false, text);
                }
            }
        });
    

提交回复
热议问题