在我的 Nuxt PWA 中,我有一个使用 this package 将我的 HTML 转换为 Canvas 的函数。 .生成的图像以 64 为基数。现在我希望能够通过以下方式共享该图像:Whatsapp、Facebook、电子邮件、Instagram 等。我找到了几个包,但它们似乎都不支持仅共享 URL 和文本文件。
这是我的分享功能:
shareTicket(index) {
html2canvas(this.$refs['ticket-' + index][0], {
backgroundColor: '#efefef',
useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem
}).then((canvas) => {
let url = canvas.toDataURL('image/png') // finally produced image url
if (navigator.share) {
navigator.share({
title: 'Title to be shared',
text: 'Text to be shared',
url: this.url,
})
}
})
当我拿出if (navigator.share)
条件我在控制台中收到一个错误 navigator.share
不是函数。我在某处读到它只适用于 HTTPS,所以我上传到我的登台服务器并尝试但仍然遇到同样的错误。为了清楚起见,我希望能够共享生成的图像本身而不是 URL。
最佳答案
告诉我此 URL 是否适合您:https://nuxt-share-social-media.netlify.app
如果是,您可以在此处找到 Github 存储库:https://github.com/kissu/so-share-image-bounty
代码是
<template>
<div>
<div id="capture" ref="element" style="padding: 10px; background: #f5da55">
<h4 style="color: #000">Hello world!</h4>
</div>
<br />
<br />
<button @click="share">share please</button>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
export default {
methods: {
share() {
// iife here
;(async () => {
if (!('share' in navigator)) {
return
}
// `element` is the HTML element you want to share.
// `backgroundColor` is the desired background color.
const canvas = await html2canvas(this.$refs.element)
canvas.toBlob(async (blob) => {
// Even if you want to share just one file you need to
// send them as an array of files.
const files = [new File([blob], 'image.png', { type: blob.type })]
const shareData = {
text: 'Some text',
title: 'Some title',
files,
}
if (navigator.canShare(shareData)) {
try {
await navigator.share(shareData)
} catch (err) {
if (err.name !== 'AbortError') {
console.error(err.name, err.message)
}
}
} else {
console.warn('Sharing not supported', shareData)
}
})
})()
},
},
}
</script>
灵感来自@denvercoder9!有关答案的更多信息
method
中效果很好语境! async
因为 ESlint,如果你想在 $refs
因为这就是你应该如何在 Vue 生态系统中选择 DOM 的特定部分 v91
) 上对其进行了测试,效果非常好! 兼容性
这是我对浏览器的体验(在 MDN 示例和我的应用程序上进行了测试,结果完全相同)
在哪里
在职的
iPad Chrome
是的
iPad 火狐
是的
iPad 游猎
是的
window Chrome
是的
火狐
不
安卓 Chrome
是的
安卓火狐
不
桌面 linux Chrome
不
桌面 linux 火狐
不
对我来说,这是一个仅限移动设备的功能(如 Android)。但看起来甚至一些桌面浏览器也在处理这个问题。我不得不承认,即使在 Windows 上看到这一项工作,我也感到非常惊讶。
这是来自 Google 的一篇有趣的帖子,与此兼容性相关:https://web.dev/web-share/#browser-support
再次阅读MDN,它说
The navigator.share() method of the Web Share API invokes the native sharing mechanism of the device.
所以,我猜“(桌面)设备”大多不支持 Share API。
TLDR:这完全按预期工作,但到目前为止兼容性真的很差。
关于javascript - 通过 PWA 的社交媒体分享图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68362603/