【发布时间】:2022-07-21 20:32:56
【问题描述】:
我有一个反应文件,使用带有 navigatorClipboard 和 documentExec 命令的 copyText。但是在 Safari 中,当调用以异步模式结束时,两者都不起作用。 这是在代码沙箱中创建的示例:
https://codesandbox.io/s/goofy-worker-rypyr?file=/src/App.js
let textArea;
const isOS = () => navigator.userAgent.match(/ipad|iphone/i);
const selectText = (text) => {
textArea = document.createElement("textArea");
textArea.value = text;
document.body.appendChild(textArea);
if (isOS()) {
const range = document.createRange();
range.selectNodeContents(textArea);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
};
const copyToClipboard = () => {
const success = document.execCommand("copy");
console.log(success);
document.body.removeChild(textArea);
};
const copyExecText = (text) => {
selectText(text);
copyToClipboard();
};
const copyNavText = (text) => {
navigator.clipboard.writeText(text).then(
() => {
console.log("Async: Copying to clipboard was successful!");
},
(err) => {
console.error("Async: Could not copy text: ", err);
}
);
};
export { copyExecText, copyNavText };
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const makeCopyText = async () => {
await wait(1000);
copyNavText("Non Sync copy text with Navigator!");
};
const makeCopyTextExec = async () => {
await wait(1000);
copyExecText("Non Sync copy text with exec!");
};
<div>
<button onClick={makeCopyTextExec}>Async Copy Exec Text</button>
<button onClick={makeCopyText}>Copy Nav Text</button>
</div>
理想情况下,我正在尝试从 API(异步方式)获取复制上下文并将其放入剪贴板。 Safari 直接拒绝了这两个功能,我无法将内容放入剪贴板。但是 Chrome 和 Firefox 都可以正常工作。
请告诉我有什么方法可以让 Safari 在异步模式下工作。
【问题讨论】:
-
请在问题中插入相关代码。不,如果您在执行请求时没有处理用户手势,Safari 不会让您写入剪贴板。您需要在用户与页面交互之前执行异步请求(或要求他们交互两次)。
-
你有想过这个吗?遇到同样的问题
标签: javascript safari clipboard navigator