Detect the Content Type in the Clipboard - Exotic Digital Access
  • Kangundo Road, Nairobi, Kenya
  • support@exoticdigitalaccess.co.ke
  • Opening Time : 07 AM - 10 PM
How to Internationalize Numbers with JavaScript

Detect the Content Type in the Clipboard


A user’s clipboard is a “catch all” between the operating system and the apps employed on it. When you use a web browser, you can highlight text or right-click an image and select “Copy Image”. That made me think about how developers can detect what is in the clipboard.

You can retrieve the contents of the user’s clipboard using the navigator.clipboard API. This API requires user permission as the clipboard could contain sensitive data. You can employ the following JavaScript to get permission to use the clipboard API:

const result = await navigator.permissions.query({name: "clipboard-write"});
if (result.state === "granted" || result.state === "prompt") {
  // Clipboard permissions available
}

With clipboard permissions granted, you query the clipboard to get a ClipboardItem instance with details of what’s been copied:

const [item] = await navigator.clipboard.read();

// When text is copied to clipboard....
item.types // ["text/plain"]

// When an image is copied from a website...
item.types // ["text/html", "image/png"]

Once you know the contents and the MIME type, you can get the text in clipboard with readText():

const content = await navigator.clipboard.readText();

In the case of an image, if you have the MIME type and content available, you can use <img> with a data URI for display. Knowing the contents of a user’s clipboard can be helpful when presenting exactly what they’ve copied!

  • Detect the Content Type in the Clipboard

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don’t work in Firefox or Internet Explorer (correctly so, by spec) though…

  • Detect the Content Type in the Clipboard
  • Detect the Content Type in the Clipboard

    More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple “file” INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can’t imagine how annoyed my users would be.  Luckily Safari, Chrome…

  • Detect the Content Type in the Clipboard

    I often incorporate tools into my customers’ websites that allow them to have some control over the content on their website. When doing so, I offer some tips to my clients to help them keep their website in good shape. One of the tips…



Source link

Leave a Reply