0

I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>
Ian Ash
  • 1,087
  • 11
  • 23
Harry
  • 621
  • 3
  • 9
  • 21
  • Does this answer your question? [Get current clipboard content?](https://stackoverflow.com/questions/6413036/get-current-clipboard-content) – WorksLikeACharm Feb 14 '20 at 10:15
  • @WorksLikeACharm Thanks for the reply. I can get this, I just can't use this function when I click the button. If you do ctrl v it works perfectly – Harry Feb 14 '20 at 10:18
  • 3
    You are sending a `ClickEvent` inside `(click)="onPaste($event)"`. Not the expected `ClipboardEvent`. So this obviously won't work. – Carsten Feb 14 '20 at 10:21

2 Answers2

1

They're not the same events: When you click a MouseEvent is emitted, when you use ctrl+v a ClipboardEvent event is emitted. MouseEvent does not have clipbordData param, thus your error.

enter image description here

To get access to the clipboard on click you'll need to use the Clipboard API that will ask for access permissions.

  onPaste(e: ClipboardEvent) {
    console.log(e);
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
  }

  clickPaste() {
    navigator.clipboard.readText().then(clipboard => alert(clipboard));
  }

Stackblitz

YounesM
  • 2,279
  • 15
  • 28
  • Thanks a lot for the help ! I think you put the wrong link, this is the same as the post – Harry Feb 14 '20 at 11:35
  • That way it works and I get the "image text" is there any way to get the blob, if you try to copy an image and not its address and paste it? – Harry Feb 14 '20 at 12:11
0

On CTRL-V you get event of type ClipboardEvent which has clipboardData on it. While your click event is of type MouseEvent which has no clipboardData on it.

I've created a stackblitz demo to reproduce it , you can try for yourself.

Anand Bhushan
  • 765
  • 8
  • 18