Friday 1 May 2020

Read data from clipboard

ClipboardJavaScript

Let us check how we can read data from clipboard using simple JavaScript. There can be many scenarios where data is available in clipboard and we have to read and use that in our application.

Copy data from clipboard

Check below simple code.


<button (click)="getDataFromClipBoard($event)">Grt clipboard data</button>


public getDataFromClipBoard(event: ClipboardEvent): void {
    navigator['clipboard'].readText().then((data) => {
      console.log(data);
    });
  }

Copy some data to clipboard and invoke above method. You can see the data in console. If your code is not working in IE, please use like below.


public getDataFromClipBoard(event: ClipboardEvent): void {
    const isIEorEdge = /msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
    const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (isIEorEdge) {
      const data = event.clipboardData || window['clipboardData'];
      const clipboardData = data.getData('text');
      console.log(clipboardData);
    } else {
      navigator['clipboard'].readText().then((data) => {
        console.log(data);
      });
    }
  }

Here we have differentiated the logic based on the browser.

In this article we have discussed about reading data from clipboard.

Related Info

1. File/image upload and send data to backend

2. Show preview image while uploading

No comments :

Post a Comment