Interact with the clipboard
Working with the clipboard in extensions is transitioning from the Web APIdocument.execCommand method (which is deprecated) to thenavigator.clipboard method.
Note:Thenavigator.clipboard API is a recent addition to the specification and may not be fully implemented in all browsers. This article describes some limitations, but be sure to review the compatibility tables for each method before using them to ensure that the API supports your needs.
The difference between the two APIs is thatdocument.execCommand this is analogous to the keyboard copy, cut, and paste actions – exchanging data between a webpage and clipboard – whereasnavigator.clipboard writes and reads arbitrary data to and from the clipboard.
navigator.clipboard provide separate methods to read or write:
- text content, using
navigator.clipboard.readText()andnavigator.clipboard.writeText(). - images, rich text, HTML, and other rich content, using
navigator.clipboard.read()andnavigator.clipboard.write().
However, whilenavigator.clipboard.readText() andnavigator.clipboard.writeText() work on all browsers,navigator.clipboard.read() andnavigator.clipboard.write() do not. For example, on Firefox at the time of writing,navigator.clipboard.read() andnavigator.clipboard.write() are not fully implemented, such that to:
- work with images use
browser.clipboard.setImageData()to write images to the clipboard anddocument.execCommand("paste")to paste images to a webpage. - write rich content (such as, HTML, rich text including images, etc.) to the clipboard, use
document.execCommand("copy")ordocument.execCommand("cut"). Then, eithernavigator.clipboard.read()(recommended) ordocument.execCommand("paste")to read the content from the clipboard.
In this article
Writing to the clipboard
This section describes the options for writing data to the clipboard.
Using the Clipboard API
The Clipboard API writes arbitrary data to the clipboard from your extension. Using the API requires the permission"clipboardRead" or"clipboardWrite" in yourmanifest.json file. As the API is only available toSecure Contexts, it cannot be used from a content script running onhttp:-pages, onlyhttps:-pages.
For page scripts, the"clipboard-write" permission needs to be requested using the Web APInavigator.permissions. You can check for that permission usingnavigator.permissions.query():
navigator.permissions.query({ name: "clipboard-write" }).then((result) => { if (result.state === "granted" || result.state === "prompt") { /* write to the clipboard now */ }});Note:Theclipboard-write permission name is not supported in Firefox, only Chromium browsers.
This function takes a string and writes it to the clipboard:
function updateClipboard(newClip) { navigator.clipboard.writeText(newClip).then( () => { /* clipboard successfully set */ }, () => { /* clipboard write failed */ }, );}Using execCommand()
The"cut" and"copy" commands of thedocument.execCommand() method are used to replace the clipboard's content with the selected material. These commands can be used without any special permission in short-lived event handlers for a user action (for example, a click handler).
For example, suppose you've got a popup that includes the following HTML:
<input type="text" /> <button>Copy</button>To make the"copy" button copy the contents of the<input> element, you can use code like this:
function copy() { let copyText = document.querySelector("#input"); copyText.select(); document.execCommand("copy");}document.querySelector("#copy").addEventListener("click", copy);Because theexecCommand() call is inside a click event handler, you don't need any special permissions.
However, let's say that instead you trigger the copy from an alarm:
function copy() { let copyText = document.querySelector("#input"); copyText.select(); document.execCommand("copy");}browser.alarms.create({ delayInMinutes: 0.1,});browser.alarms.onAlarm.addListener(copy);Depending on the browser, this may not work. On Firefox, it will not work, and you'll see a message like this in your console:
document.execCommand('cut'/'copy') was denied because it was not called from inside a short running user-generated event handler.
To enable this use case, you need to ask for the"clipboardWrite"permission. So:"clipboardWrite" enables you to write to the clipboard outside a short-lived event handler for a user action.
Note:document.execCommand() does not work on input fields oftype="hidden", with the HTML5 attribute"hidden", or any matching CSS rule using"display: none;". So, to add a "copy to clipboard" button to aspan,div, orp tag, you need to use a workaround, such as setting the input's position to absolute and moving it out of the viewport.
Browser-specific considerations
The clipboard and other APIs involved here are evolving rapidly, so there are variations among browsers in how they work.
In Chrome:
- You don't need
"clipboardWrite", even to write to the clipboard outside a user-generated event handler.
In Firefox:
navigator.clipboard.write()is not supported.
See thebrowser compatibility tables for more information.
Reading from the clipboard
This section describes the options for reading or pasting data from the clipboard.
Using the Clipboard API
The Clipboard API'snavigator.clipboard.readText() andnavigator.clipboard.read() methods let you read arbitrary text or binary data from the clipboard insecure contexts. This lets you access the data in the clipboard without pasting it into an editable element.
Once you have the"clipboard-read" permission from thePermissions API, you can read from the clipboard easily. For example, this snippet of code fetches the text from the clipboard and replaces the contents of the element with the ID"outbox" with that text.
navigator.clipboard .readText() .then((clipText) => (document.getElementById("outbox").innerText = clipText));Using execCommand()
To usedocument.execCommand("paste") your extension needs the"clipboardRead"permission. This is the case even if you're using the"paste" command from within a user-generated event handler, such asclick orkeypress.
Consider HTML that includes something like this:
<textarea></textarea> <button>Paste</button>To set the content of the<textarea> element with the ID"output" from the clipboard when the user clicks the"paste"<button>, you can use code like this:
function paste() { let pasteText = document.querySelector("#output"); pasteText.focus(); document.execCommand("paste"); console.log(pasteText.textContent);}document.querySelector("#paste").addEventListener("click", paste);Browser-specific considerations
Firefox supports the"clipboardRead"permission from version 54 but only supports pasting into elements incontent editable mode, which for content scripts only works with a<textarea>. For background scripts, any element can be set to content editable mode.