剪贴板API-以html格式返回值



是否可以从剪贴板中获取HTML格式的文本?下面的代码以纯文本形式返回文本。

navigator.clipboard.readText()
.then(text => {
console.log(text);
})
.catch(err => {
console.log('Something went wrong', err);
})

要读取剪贴板中的任何HTML,您可以使用navigator.clipboard.read方法,在提供HTML的结果数组中找到ClipboardItem(如果有(,然后从项目中读取该HTML,如下所示:

/**
* Read any HTML from the clipboard.
*
* @returns A promise that will be fulfilled with the HTML or `undefined` if none
*          is available, or that will be rejected if any error occurs reading
*          the clipboard (such as permission from the user being denied).
*/
async function readClipboardHTML() {
const items = await navigator.clipboard.read();
const htmlItem = items.find(({types}) => types.includes("text/html"));
if (htmlItem) {
const htmlBlob = await htmlItem.getType("text/html");
const html = await htmlBlob.text();
return html;
}
}

请注意,您需要获得页面用户的权限才能以这种方式访问剪贴板。(这就是为什么我没有做Stack Snippet——它们是沙盒的,不允许浏览器向用户请求权限。(

以下是一个示例,您可以复制并粘贴到localhost上运行,以查看其工作情况(因为它似乎基本上是所有在线服务的沙盒,因此甚至无法请求权限(:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Clipboard HTML Demonstration</title>
<style>
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.error {
color: #d00;
}
</style>
</head>
<body>
<p>You can <strong>copy this paragraph</strong> to make sure you have HTML in your clipboard.</p>
<input type="button" id="btn" value="Get Clipboard HTML">
<script type="module" src="./clipboard-example.js"></script>
<div id="result"></div>
</script>
</body>
</html>

JavaScript:

/**
* Read any HTML from the clipboard.
*
* @returns A promise that will be fulfilled with the HTML or `undefined` if none
*          is available, or that will be rejected if any error occurs reading
*          the clipboard (such as permission from the user being denied).
*/
async function readClipboardHTML() {
const items = await navigator.clipboard.read();
const htmlItem = items.find(({types}) => types.includes("text/html"));
if (htmlItem) {
const htmlBlob = await htmlItem.getType("text/html");
const html = await htmlBlob.text();
return html;
}
}
const btn = document.getElementById("btn");
const result = document.getElementById("result");
btn.addEventListener("click", () => {
result.classList.remove("error");
result.textContent = "";
readClipboardHTML()
.then((html) => {
if (typeof html === "undefined") {
result.textContent = `No HTML available in the clipboard`;
} else {
result.textContent = `HTML: ${html}`;
}
})
.catch((error) => {
result.classList.add("error");
result.textContent = `Error: ${String(error)}`;
});
});

最新更新