navigator.clipboard.write : 'Clipboard': Iterator getter is not callable
Asked Answered
E

2

11

I am trying to use navigator.clipboard.write(blob) to copy a DOMString to the clipboard. I am able to use clipboard.writeText('text') and have it copy, but I am needing text/html.

Example that is failing:

const copy = async () => {
 await navigator.permissions.query({name: "clipboard-write"}).then(result => {
    if (result.state == "granted" || result.state == "prompt") {
        const data = new Blob(['<div>test</div>'], {type : 'text/html'})
        navigator.clipboard.write(data);
    }
})}

When I run it, I get the following error:

Uncaught (in promise) TypeError: Failed to execute 'write' on 'Clipboard': Iterator getter is not callable.

I have also tried changing text/html to text/plain, which I thought would make it function the same as writeText but did not.

I then attempted wrapping the blob in a new ClipboardItem which I found from a another question:

const data = new Blob(['<div>test</div>'], {type: 'text/html'})
const item = new ClipboardItem({'text/html': data});
navigator.clipboard.write(item);

Any guidance would be appreciated.

Edveh answered 9/10, 2019 at 20:47 Comment(0)
P
11

According to https://www.w3.org/TR/clipboard-apis/#clipboard-interface, Clipboard.write takes a sequence of ClipboardItems. Have you tried something like this instead?

navigator.clipboard.write([item]);

However, note that Chrome (79.0.3945.2/Canary, at the time of writing) does not seem to support writing “text/html” via the clipboard API yet — only “text/plain” and “image/png”.

Palisade answered 19/10, 2019 at 20:51 Comment(1)
Copying as text/html works as of Chrome (95.0.4638.69)Laguna
S
1

I spent SO many hours on this and FINALLY figured it out! This works on Chrome, but have no clue if on other browsers. It is all about the event.clipboardData.setData. Hope this helps!

var textString = 'This is plain text';
var htmlString = `<p>${textString}
    new line here</p><p>new paragraph</p>`;
var clipboardDataEvt = event.clipboardData;
clipboardDataEvt.setData('text/plain', textString);
clipboardDataEvt.setData('text/html', htmlString);

Make sure it is wrapped within a event listener for the clipboard like Cut, Copy, or Paste as I believe that is what gives you access to the clipboardData event with something like:

document.addEventListener('cut', function (e){});
Squeegee answered 7/5, 2020 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.