新版 API
MDN 文档地址: Clipboard API - Web API | MDN
该 API 被设计用来取代使用 document.execCommand() 的剪贴板访问方式。
write 方法
这里只讨论如何进行复制
假设页面上有这样的 html 代码。
html
<div class="md-preview">
<el-button type="primary" @click="copyDom">复制</el-button>
<section id="output">
<!- 需要复制的区域-->
</section>
</div>
复制到剪贴版总共需要三个步骤:
- 获取 DOM 元素
- 构建 ClipboardItem 参数
- 写入剪贴版
javascript
async function copy() {
const dom = document.getElementById("output");
try {
const htmlContent = dom?.innerHTML;
const htmlBlob = new Blob([htmlContent || ""], { type: "text/html" });
const clipboardItem = new ClipboardItem({ "text/html": htmlBlob });
await navigator.clipboard.write([clipboardItem]);
} catch (error) {
console.log(error);
}
}
可以将这个函数放进按钮的点击事件里。
旧版 API
由于旧版 API 已经在 MDN 上声明
遗弃了,能不使用就不用。
MDN 文档:document.execCommand - Web API | MDN
已弃用: 不再推荐使用该特性。虽然一些浏览器仍然支持它,但也许已从相关的 web 标准中移除,也许正准备移除或出于兼容性而保留。请尽量不要使用该特性,并更新现有的代码;参见本页面底部的兼容性表格以指导你作出决定。请注意,该特性随时可能无法正常工作。
这里给出参考代码:旧版 API 不支持 async/await 方式。
js
const dom = document.getElementById("output");
dom?.focus();
window.getSelection()?.removeAllRanges();
const range = document.createRange();
if (dom && dom.firstChild && dom.lastChild) {
range.setStartBefore(dom.firstChild);
range.setEndAfter(dom.lastChild);
window.getSelection()?.addRange(range);
document.execCommand("copy");
window.getSelection()?.removeAllRanges();
}
注意:一旦建立了 Range 对象,在使用它的大多数方法之前需要设置它的边界点。
拓展
由于新版 API 的使用必须处于安全上下文环境中,即只能用 https 或 localhost 进行访问。
读取剪贴版内容,浏览器会弹出权限框,让用户选择是否"允许读取剪贴版"。