How to detect Ctrl+V, Ctrl+C using JavaScript?

前端 未结 17 2121
走了就别回头了
走了就别回头了 2020-11-22 13:47

How to detect ctrl+v, ctrl+c using Javascript?

I need to restrict pasting in my textareas, end user should not copy and p

17条回答
  •  佛祖请我去吃肉
    2020-11-22 14:39

    There's another way of doing this: onpaste, oncopy and oncut events can be registered and cancelled in IE, Firefox, Chrome, Safari (with some minor problems), the only major browser that doesn't allow cancelling these events is Opera.

    As you can see in my other answer intercepting Ctrl+v and Ctrl+c comes with many side effects, and it still doesn't prevent users from pasting using the Firefox Edit menu etc.

    function disable_cutcopypaste(e) {
        var fn = function(evt) {
            // IE-specific lines
            evt = evt||window.event
            evt.returnValue = false
    
            // Other browser support
            if (evt.preventDefault) 
                evt.preventDefault()
            return false
        }
        e.onbeforepaste = e.onbeforecopy = e.onbeforecut = fn
        e.onpaste = e.oncopy = e.oncut = fn
    }
    

    Safari still has some minor problems with this method (it clears the clipboard in place of cut/copy when preventing default) but that bug appears to have been fixed in Chrome now.

    See also: http://www.quirksmode.org/dom/events/cutcopypaste.html and the associated test page http://www.quirksmode.org/dom/events/tests/cutcopypaste.html for more information.

提交回复
热议问题