如何粘贴文本

现代方法

使用异步剪贴板 API

要以编程方式从用户的剪贴板读取文本,例如,在按钮点击后,您可以使用 readText() 方法,该方法属于 异步剪贴板 API。如果尚未授予读取剪贴板的权限,则首次调用 navigator.clipboard.readText() 时将请求该权限。

const pasteButton = document.querySelector('#paste-button');

pasteButton.addEventListener('click', async () => {
   try {
     const text = await navigator.clipboard.readText()
     document.querySelector('textarea').value += text;
     console.log('Text pasted.');
   } catch (error) {
     console.log('Failed to read clipboard');
   }
});

浏览器支持

  • Chrome: 66.
  • Edge: 79.
  • Firefox: 125.
  • Safari: 13.1.

来源

经典方法

使用 document.execCommand()

通过使用 document.execCommand('paste'),您可以将剪贴板内容粘贴到插入点(当前聚焦的 HTML 元素)。execCommand 方法返回一个布尔值,指示 paste 事件是否成功。但是,此方法存在局限性,例如,由于它是同步的,因此粘贴大量数据可能会阻止页面。

pasteButton.addEventListener('click', () => {
  document.querySelector('textarea').focus();
  const result = document.execCommand('paste')
  console.log('document.execCommand result: ', result);
})

浏览器支持

  • Chrome: 1.
  • Edge: 12.
  • Firefox: 69.
  • Safari: 1.3.

来源

渐进增强

pasteButton.addEventListener('click', async () => {
   try {
     const text = await navigator.clipboard.readText()
     document.querySelector('textarea').value += text;
     console.log('Text pasted.');
   } catch (error) {
     console.log('Failed to read clipboard. Using execCommand instead.');
     document.querySelector('textarea').focus();
     const result = document.execCommand('paste')
     console.log('document.execCommand result: ', result);
   }
});

延伸阅读

演示

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    />
    <title>How to paste text</title>
  </head>
  <body>
    <h1>How to paste text</h1>
    <p>
      <button type="button">Paste</button>
    </p>
    <textarea></textarea>
  </body>
</html>

CSS


        :root {
  color-scheme: dark light;
}

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
  font-family: system-ui, sans-serif;
}

button {
  display: block;
}
        

JS


        const pasteButton = document.querySelector('button');

pasteButton.addEventListener('click', async () => {
  try {
    const text = await navigator.clipboard.readText()
    document.querySelector('textarea').value += text;
    console.log('Text pasted.');
  } catch (error) {
    console.log('Failed to read clipboard. Using execCommand instead.');
    document.querySelector('textarea').focus();
    const result = document.execCommand('paste')
    console.log('document.execCommand result: ', result);
  }
});