Sunday, May 5, 2024
HomeTechnologySoftwareDetect the Content Type in the Clipboard

Detect the Content Type in the Clipboard

Date:

Related stories

Lesson Learned: What Goes Around Comes Around

At Inman Connect Las Vegas, July 30-Aug. 1,...

The Best And Worst Parts Of Every Star Wars Movie

Best: Picking just one best thing from Empire...

Chicken Bacon Ranch Casserole Recipe

This website may contain affiliate links and advertising...

Junkyard Gem: 1997 Saab 9000 CS

With all the junkyard Saab history we've seen...
spot_imgspot_img

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!

  • How to Create a Twitter Card
  • 5 HTML5 APIs You Didn&#8217;t Know Existed

    When you say or read “HTML5”, you half expect exotic dancers and unicorns to walk into the room to the tune of “I’m Sexy and I Know It.”  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature…



Source link

Latest stories

spot_img