-
-
Save openmynet/d7e3ffcada35e6cb7f975f3a11033b84 to your computer and use it in GitHub Desktop.
html copyToWechat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function copyToWechat(html = "") { | |
async function imageToBlob(src) { | |
// 可以搞定跨域问题的话也可以使用 | |
// const resp= await fetch(src) | |
// return resp.blob() | |
return new Promise((ok, error) => { | |
const canvas = document.createElement("CANVAS"); | |
const ctx = canvas.getContext("2d"); | |
const img = new Image(); | |
img.src = src; | |
img.crossOrigin = "Anonymous"; // 注意跨域资源的处理 | |
img.onload = function () { | |
canvas.width = img.width; | |
canvas.height = img.height; | |
ctx.drawImage(img, 0, 0); | |
canvas.toBlob(ok); | |
}; | |
img.onerror = error; | |
}); | |
} | |
const div = document.createElement("div"); | |
div.innerHTML = html; | |
Array.from(div.querySelectorAll("style,script")).forEach((node) => { | |
node.parentElement.removeChild(node); | |
}); | |
const plain = div.textContent.trim(); | |
const image = await Array.from(div.querySelectorAll("img")) | |
.filter((img) => img.src) | |
.slice(0, 1) | |
.map((img) => imageToBlob(img.src))[0]; | |
if (typeof ClipboardItem !== "undefined") { | |
console.log("clipboard.api"); | |
// https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem | |
// chrome 系列浏览器生效 | |
const text = new Blob([plain], { type: "text/plain" }); | |
let config = { [text.type]: text }; | |
if (image) { | |
config[image.type] = image; | |
} | |
const data = new ClipboardItem(config); | |
// 受操作系统限制windows下不支持 navigator.clipboard.write([data, data2, data3]); | |
await navigator.clipboard.write([data]); | |
} else { | |
function listener(e) { | |
console.log("old.clipboard.api"); | |
// https://developer.mozilla.org/zh-CN/docs/Web/API/DataTransfer/setData | |
// clipboardData.setData(DOMString, DOMString) | |
// 不支持复制图片 | |
e.clipboardData.setData("text/plain", plain); | |
e.preventDefault(); | |
} | |
document.addEventListener("copy", listener); | |
document.execCommand("copy"); | |
document.removeEventListener("copy", listener); | |
} | |
} | |
// test | |
temp1 = document.querySelector("#article-root"); | |
temp1.addEventListener("click", () => { | |
copyToWechat(temp1.innerHTML) | |
.then((_) => { | |
console.log("ok"); | |
}) | |
.catch((e) => console.error(e)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment