Items written to clipboard by Navigator.clipboard.write() could not be pasted correctly

48 views Asked by At

Here is what I meant to do: user selects the content on the web page, the content automatically copied to the clipboard.

THE CODE IS:

    function createHtmlBlob(target) {
        return new Blob([target], {type: "text/html"});
    }

    async function writeDataToClipboard(blob) {
        if (navigator.clipboard && navigator.clipboard.write) {
            try {
                const item = new ClipboardItem({
                    [blob.type]: blob,
                });
                await navigator.clipboard.write([item]);
            } catch (error) {
                console.error("failed to copy", error);
            }
        }
    }

    function copy() {
        writeDataToClipboard(createHtmlBlob(someHtmlString))
    }

someHtmlString is like

this is a text
<p>this is a paragraph</p>
<ul><li>xxx</li></ul>

THE PROBLEM IS:

I could paste things written to clipboard into Microsoft Word(windows) or LibreOffice Writer(linux) by pressing CTRL V, but I can't paste them into notepad.exe in windows, or Intellij Idea.

WHAT I TRIED:

  1. I tried document.execCommand('copy'), and nothing changed.
  2. I'm new to this api, I looked up in https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/clipboard and failed to figure it out.

Why is that? What did I miss? If HTML(not plain text) is the reason why it didn't work in nodepad.exe, why Intellij Idea can't recognize them either?

Help is needed, sexy guys!

0

There are 0 answers