gpt4 book ai didi

javascript - Web 共享 API 级别 2 DOMException : Permission denied

转载 作者:行者123 更新时间:2023-12-01 15:21:44 30 4
gpt4 key购买 nike

我正在获取一个 img,将其转换为文件,然后尝试共享该文件。我在 Android 上最新的 Chrome 上测试了代码(目前唯一支持此 API 的浏览器)。

  if (shareimg && navigator.canShare) {
share = async function() {
const response = await fetch(shareimg);
const blob = await response.blob();
const file = await new File([blob], "image.jpeg");

navigator.share({
url: shareurl,
title: sharetitle,
text: sharetext,
files: [file]
});
};
}

我正在运行该函数以响应用户单击按钮(必须从用户手势调用 share() 方法,否则它将不起作用)。

(我正在使用 Browserstack 测试此代码,它为 javascript 错误提供了一个控制台,因为我无法成功地将我的 Android 设备链接到我的 mac 进行调试,并且此 API 仅适用于手机 - 不适用于桌面版 Chrome。)

最佳答案

您的代码可以稍微优化一下。当前需要指定 blob 的 MIME 类型。您可以在此处实际查看以下代码:https://statuesque-backpack.glitch.me/ .

if ('canShare' in navigator) {
const share = async function(shareimg, shareurl, sharetitle, sharetext) {
try {
const response = await fetch(shareimg);
const blob = await response.blob();
const file = new File([blob], 'rick.jpg', {type: blob.type});

await navigator.share({
url: shareurl,
title: sharetitle,
text: sharetext,
files: [file]
});
} catch (err) {
console.log(err.name, err.message);
}
};

document.querySelector('button').addEventListener('click', () => {
share(
'https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Rick_Astley_Dallas.jpg/267px-Rick_Astley_Dallas.jpg',
'https://en.wikipedia.org/wiki/Rick_Astley',
'Rick Astley',
'Never gonna give you up!'
);
});
}

关于javascript - Web 共享 API 级别 2 DOMException : Permission denied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58766220/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com