navigator.clipboard.write and HTML

Tried to write a bit of rich-text HTML to the user’s clipboard like this:

const html = "<p>Hello <strong>world!</strong></p>";
const clipboardItemData = {
    ["text/html"]: html
};
const clipboardItem = new ClipboardItem(clipboardItemData);
await navigator.clipboard.write([clipboardItem]);

That worked fine in Firefox but in Chrome the page simply crashed. STATUS_ACCESS_VIOLATION was all it said. Debugging showed that navigator.clipboard.write() caused the crash. There were no issues with creating the ClipboardItem.

It turns out that for Chrome it’s really necessary to first create a blob from the HTML string:

const html = "<p>Hello <strong>world!</strong></p>";
const blobHtml = new Blob([html], { type: "text/html" });
const clipboardItemData = {
    ["text/html"]: blobHtml
};
const clipboardItem = new ClipboardItem(clipboardItemData);
await navigator.clipboard.write([clipboardItem]);

Et voilĂ , the rich text will be on the clipboard.

Please note that copying to clipboard is only possible when initiated by a user, i.e. in the handler of a click event.

Leave a Reply

Your email address will not be published. Required fields are marked *

This form collects your name, email address and content so that we can keep track of the comments placed on the website. Check our privacy policy for more info on where, how and why we store your data.