长话短说
即使 writeText()
是用户事件的直接结果,是否有可能让剪贴板 API 从 Safari 中的 Axios get 请求的结果中写入文本?
长版
我有一个异步按钮点击事件,在该点击事件中我使用 Axios 获取另一个页面的 HTML。我想使用剪贴板 API 获取该字符串并将其保存到剪贴板。
这在 Chrome 和 Firefox 中有效,但在 Safari 中存在一些问题,我将在下面显示。
测试:
- Chrome 88.0.4324.192
- 火狐 78.7.1
- Safari 14.0.3
我能找到的与此类事情相关的最接近的 SO 问题是 Javascript / Clipboard API / Safari iOS / NotAllowedError Message但我觉得我的剪贴板 API 调用是在用户事件中直接调用的。
尝试 1 在 Safari 中开始工作
copyButton.addEventListener('click', async (event) => {
try {
const {data: html} = await axios.get('https://website-to-copy.com');
await navigator.clipboard.writeText(html);
console.log('copy was a success');
} catch (error) {
console.log(error);
}
});
Safari 中的结果 1
- 请求成功
- 无法写入剪贴板
- NotAllowedError:用户代理或当前上下文中的平台不允许请求,可能是因为用户拒绝了许可。
我对结果 1 的看法
当时我认为这会奏效。 writeText()
调用是用户事件的直接结果,我只是传入一个字符串...即使该字符串是 Axios get 请求的结果。当它不起作用时,我认为 get 请求一定有什么东西放弃了权限。
尝试 2 在 Safari 中开始工作
copyButton.addEventListener('click', async (event) => {
try {
const {data: html} = await axios.get('https://website-to-copy.com');
// throw in a random string thinking maybe something
// in the get request is throwing Clipboard API off
await navigator.clipboard.writeText('some random text to copy');
console.log('copy was a success');
} catch (error) {
console.log(error);
}
});
Safari 中的结果 2
- 请求成功
- 无法写入剪贴板
- NotAllowedError:用户代理或当前上下文中的平台不允许请求,可能是因为用户拒绝了许可。
我对结果 2 的看法
当我的随机文本没有被复制时,我真的很惊讶。当尝试 #1 失败时,我决定保留 get 请求,但只向 writeText()
提供一些随机文本,无论如何都与 get 请求无关,只是为了看看它是否会复制。显然 get 请求仍在影响剪贴板 API。
尝试 3 在 Safari 中开始工作
copyButton.addEventListener('click', async (event) => {
try {
// remove get request and see if i can get anything to
// copy to clipboard
//const {data: html} = await axios.get('https://website-to-copy.com');
await navigator.clipboard.writeText('some random text to copy');
console.log('copy was a success');
} catch (error) {
console.log(error);
}
});
Safari 中的结果 3
- 文本已成功复制到剪贴板
我对结果 3 的看法
很高兴我可以在 Safari 中使用剪贴板 API 成功复制文本。但是我真的很想复制 get 请求的结果。
最佳答案
copyButton.addEventListener('click', async (event) => {
try {
const { ClipboardItem } = window;
await navigator.clipboard.write([new ClipboardItem({ "text/plain": getUrl() })]).then(()=>console.log("copied"))
} catch (error) {
console.log(error);
}
});
const getUrl = () => {
const {data: html} = await axios.get('https://website-to-copy.com');
return html;
}
关于javascript - 单击事件中与axios结合使用的剪贴板API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66496294/