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

前端 未结 17 2059
走了就别回头了
走了就别回头了 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条回答
  •  Happy的楠姐
    2020-11-22 14:27

    A hook that allows for overriding copy events, could be used for doing the same with paste events. The input element cannot be display: none; or visibility: hidden; sadly

    export const useOverrideCopy = () => {
      const [copyListenerEl, setCopyListenerEl] = React.useState(
        null as HTMLInputElement | null
      )
      const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
        () => () => {}
      )
      // appends a input element to the DOM, that will be focused.
      // when using copy/paste etc, it will target focused elements
      React.useEffect(() => {
        const el = document.createElement("input")  
        // cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
        el.style.width = "0"
        el.style.height = "0"
        el.style.opacity = "0"
        el.style.position = "fixed"
        el.style.top = "-20px"
        document.body.appendChild(el)
        setCopyListenerEl(el)
        return () => {
          document.body.removeChild(el)
        }
      }, [])
      // adds a event listener for copying, and removes the old one 
      const overrideCopy = (newOverrideAction: () => any) => {
        setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
          const copyHandler = (e: ClipboardEvent) => {
            e.preventDefault()
            newOverrideAction()
          }
          copyListenerEl?.removeEventListener("copy", prevCopyHandler)
          copyListenerEl?.addEventListener("copy", copyHandler)
          copyListenerEl?.focus() // when focused, all copy events will trigger listener above
          return copyHandler
        })
      }
      return { overrideCopy }
    }
    

    Used like this:

    const customCopyEvent = () => {
        console.log("doing something")
    } 
    const { overrideCopy } = useOverrideCopy()
    overrideCopy(customCopyEvent)
    

    Every time you call overrideCopy it will refocus and call your custom event on copy.

提交回复
热议问题