You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何通过按钮实现剪贴板粘贴功能?

Trigger Paste from Clipboard via Button Click

Great question! The window.clipboardData API you tried is an old IE-specific feature, which is why it’s not working in modern browsers. Luckily, the Clipboard API (a standard web API) lets you read from the clipboard with just a button click—here’s how to implement it alongside your existing copy functionality:

First, let’s update your copy function to use the modern Clipboard API (since document.execCommand('copy') is deprecated, though it still works in most browsers):

async function copy(val) {
  try {
    await navigator.clipboard.writeText(val);
    console.log('Text copied to clipboard!');
  } catch (err) {
    console.error('Failed to copy text:', err);
    alert('Copy failed—please try again.');
  }
}

Step 2: Add the Paste Function

This function uses navigator.clipboard.readText() to fetch content from the clipboard, triggered directly by a button click:

async function pasteFromClipboard() {
  try {
    // Request permission and read clipboard text
    const pastedText = await navigator.clipboard.readText();
    
    // Do something with the pasted text (example: display it in a div)
    const outputElement = document.getElementById('paste-output');
    outputElement.textContent = `Pasted content: ${pastedText}`;
  } catch (err) {
    console.error('Failed to paste text:', err);
    alert('Could not access clipboard. Make sure you allowed permission and there’s text to paste.');
  }
}

Step 3: HTML Buttons (Separate or Combined)

Separate Buttons

If you want distinct copy and paste buttons:

<button onclick="copy('Your text to copy here')">Copy Text</button>
<button onclick="pasteFromClipboard()">Paste Text</button>
<div id="paste-output"></div>

Same Button for Both Actions

To use the same button to toggle between copy and paste:

let isCopyMode = true;

async function toggleCopyPaste(val) {
  const button = event.target;
  if (isCopyMode) {
    await copy(val);
    button.textContent = 'Paste';
    isCopyMode = false;
  } else {
    await pasteFromClipboard();
    button.textContent = 'Copy';
    isCopyMode = true;
  }
}
<button onclick="toggleCopyPaste('Your text to copy here')">Copy</button>
<div id="paste-output"></div>

Key Notes

  • Permissions: The browser will prompt users for clipboard access the first time they click the paste button—this is a security requirement, and the button click counts as valid user interaction (which is mandatory for clipboard access).
  • HTTPS Requirement: The Clipboard API works over HTTPS (except for localhost during development).
  • Browser Support: All modern browsers (Chrome, Firefox, Edge, Safari) support this API.

内容的提问来源于stack exchange,提问作者Terrance Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:12