navigator.clipboard API

By  on  

Reading from and writing to the user's clipboard can be both a very useful and dangerous capability. Used correctly and it's a huge convenience to the user; used dubiously and the user could suffer catastrophic consequences. Imagine a wrong account number or wallet address being copied -- yikes! This is why programmatic copy and pasting needs to be protected, and why the JavaScript Clipboard API requires explicit user permission to allow a website to use it.

To read to the user's clipboard, you use the readText method:

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

To write to the user's clipboard, you use the writeText method:

await navigator.clipboard.writeText('');

The API is obviously very easy to use -- each method returns a Promise so you can use async/await or then callbacks. The difficult part is striking the balance of when to use each. Unnecessary reads will feel invasive, and unnecessary writes will significantly dissolve user trust.

When may you want to write to the clipboard? Possibly after the user pastes a seed phrase, password, or credit card number into likewise named form fields.

Sure you can use the numerous libraries available to simulate this API, but know that an official API does exist. And as always, I'm teaching you how to use it -- it's up to you to ensure it's the right time and tool for the job!

Recent Features

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    Serving Fonts from CDN

    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...

Incredible Demos

  • By
    Add Controls to the PHP Calendar

    I showed you how to create a PHP calendar last week. The post was very popular so I wanted to follow it up with another post about how you can add controls to the calendar. After all, you don't want your...

  • By
    Elegant Overflow with CSS Ellipsis

    Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...

Discussion

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