Search code examples
javascriptinternet-explorercopy-paste

Is there any side-effect when using addEventListener to handle paste event in IE browser?


Recently, I've met a problem with IE browser that I can't reproduce on my browser. It's only happened in fixed computer (with a particular version, I guess so). I'm customizing copy function and using pure paste function of OS to paste the content. The problem I've figured out is when I add these code

document.addEventListener("paste", function(e) {
    if (isIE()) {
        window.clipboardData.setData("Text", window.clipboardData.getData("Text").replace(/\r?\n|\r/g, '')); //FOR IE
    }
}); 
///(using to handle the problem of break lines in IE when paste event is triggered)

Sometimes, paste function of OS didn't work well. Sometimes, it could. It pasted empty content. However, I debugged that the clipboardData content was still remained. If I remove addEventListener event, everything works well. But, I need to keep the handling of break lines in IE, too. Have anybody ever experienced this problem? Please help, thank you.


Solution

  • Finally, I have to assign the text to the Input value instead of using pure paste event of OS. IE11 doesn't support much for the Input element at this point.

    document.addEventListener("paste", function(e) {
        if (isIE()) {
            e.preventDefault();
    
            var content = window.clipboardData.getData("text").replace(/\r?\n|\r/g, ''); //FOR IE
            var replace, position = e.target.selectionEnd - e.target.selectionStart;
            // if the position is the end of the string
            if (e.target.selectionStart === $(e.target).val().length)
                replace = $(e.target).val() + content;
            else replace = $(e.target).val().replace($(e.target).val().substr(e.target.selectionStart, position), content);
    
            $(e.target)
                .val(replace)
                // Manually trigger events if you want
                .trigger('input')
                .trigger('change');
            return false;
        }
    });