Working with the clipboard in extensions is transitioning from the Web API document.execCommand
method (which is deprecated) to the navigator.clipboard
method.
Note: The navigator.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 that document.execCommand
this is analogous to the keyboard copy, cut, and paste actions – exchanging data between a webpage and clipboard – whereas navigator.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, while navigator.clipboard.readText()
and navigator.clipboard.writeText()
work on all browsers, navigator.clipboard.read()
and navigator.clipboard.write()
do not. For example, on Firefox at the time of writing, navigator.clipboard.read()
and navigator.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.