新的剪贴板 API 可以访问非“文本/纯文本”内容

Dav*_*der 2 javascript clipboard google-chrome clipboarddata

使用新的剪贴板 API,我可以轻松地以文本形式读出当前内容(示例代码),并且该 API 看起来可以支持多种“类型”,但至少在 Chrome 和 Edge 中它总是只返回text/plain。这是新 API 中的错误/限制,还是我应该以不同的方式进行调用?

如何触发此行为的完整示例

注意:请确保事先复制富文本内容。(这不是一个片段,因为新的剪贴板 API 似乎无法在 iframe 中工作)

<!DOCTYPE html>
<html>
  <head> </head>
  <body>
    <div contenteditable>
      paste into this area for old api
    </div>
    <button id="async">async api</button>
    <script>
Run Code Online (Sandbox Code Playgroud)
      document.querySelector("#async").addEventListener("click", (e) => {
        navigator.permissions
          .query({ name: "clipboard-read" })
          .then((result) => {
            // If permission to read the clipboard is granted or if the user will
            // be prompted to allow it, we proceed.

            if (result.state == "granted" || result.state == "prompt") {
              navigator.clipboard.read().then((data) => {
                console.log(data.map((d) => d.types)); // always returns only [['text/plain']]
              });
            }
          });
      });
      document.querySelector("div").addEventListener("paste", (e) => {
        console.log(e.clipboardData.types); // returns for the same content ["text/plain", "text/html"]
      });
Run Code Online (Sandbox Code Playgroud)
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 5

Chrome 仍在研究它:https://bugs.chromium.org/p/chromium/issues/detail ?id=897289

目前,通过该API只能检索text/plainimage/png写入。

不幸的是,他们还阻止了此功能对跨源框架的访问,这意味着几乎所有在线 js fiddlers,包括 Stack-Snippets。

所以这里有一个代码沙箱外部窗口的链接,不确定这些东西会持续多久,下面是该沙箱的主要代码:

  button.onclick = async (evt) => {
    const clipboard = navigator.clipboard;
    const item = (await clipboard.read())[0];
    const image =
      item.types.includes("image/png") && (await item.getType("image/png"));
    const text =
      item.types.includes("text/plain") && item.getType("text/plain");

    if (image) {
      document.body.appendChild(new Image()).src = URL.createObjectURL(
        image
      );
    }
    console.log(text);
  };
Run Code Online (Sandbox Code Playgroud)

请注意,可通过ClipboardEvent访问的同步 APIclipboardData可以访问这些类型。