This content originally appeared on David Walsh Blog and was authored by David Walsh
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!
The post Detect the Content Type in the Clipboard appeared first on David Walsh Blog.
This content originally appeared on David Walsh Blog and was authored by David Walsh
David Walsh | Sciencx (2023-03-06T10:51:14+00:00) Detect the Content Type in the Clipboard. Retrieved from https://www.scien.cx/2023/03/06/detect-the-content-type-in-the-clipboard/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.