navigator.clipboard API

By  on  

Interacting with a user's host clipboard is something web developers have wanted for both good and evil purposes. On the good side, it's nice to allow users to easily copy text like wallet addresses or branch names; for evil, copying malicious text that the user may mistakenly paste into a form and have their funds stolen -- and there are probably more evil reasons.

We used to use the document.execCommand('copy') to accomplish this task, but it was unreliable. The navigator.clipboard API provides async readText and writeText methods for managing clipboard data. Let's have a look how it works!

// Write to clipboard
document.body.addEventListener(
    "click", 
    (e) => {
        await navigator.clipboard.writeText("Yo")
    }
)

// Read from clipboard
document.body.addEventListener(
    "click", 
    (e) => {
        const text = await navigator.clipboard.readText()
    }
)

The readText and writeText methods are easy enough to use, but you can't execute this code whenever you'd like, due to browser security protocols. Oftentimes you need to use this code inside of an event listener, as a result of an action taken by the users.

I'm glad we now have an API that's async and more reliable than the gross execCommand hack of the old days. Still, I sometimes wonder how this could be exploited, because after all, you can still put any text there. Let's all do each other a solid though -- let's use this API for good, not evil!

Recent Features

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

Discussion

  1. Dan F

    In the compatibility tables on MDN https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText it says for Firefox
    “Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks”

    What’s secure contexts in this case? Just https, or some other restrictions?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!