Web编程技术营地
研究、演示、创新

Miscellaneous

撰写时间:2024-12-09

修订时间:2025-03-14

Navigator

Clipboard

pc.log(navigator.clipboard);

let textEle = document.querySelector('input'); let copyEle = document.querySelector('#copy'); let readEle = document.querySelector('#read'); let outputEle = document.querySelector('output'); async function copyToClipboard() { let type = "text/plain"; let itemData = { [type]: textEle.value }; let item = new ClipboardItem(itemData); await navigator.clipboard.write([item]); console.log('done'); } async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { const blob = await clipboardItem.getType(type); blob.text().then(text => { outputEle.textContent = text; }); } } } catch (err) { console.error(err.name, err.message); } } copyEle.addEventListener("click", copyToClipboard); readEle.addEventListener("click", getClipboardContents);

:root { color-scheme: light dark; } output { border: 1px solid Canvas; }

除了点击第1个按钮进行复制之外,还可以在浏览器中的网页内容中刷黑相应文本内容进行复制,然后点击第2个按钮直接读取出来。

如果在操作系统中复制文本内容,在网页中Chrome可直接读取;而Safari会弹出一个菜单,点击粘帖,即可读取。

本站的Web ClipBoard应用到了这里的技术。

参考资源

General

  1. ClipboardItem