按钮复制到剪贴板 window 位置 href
Button Copy to Clipboard window location href
我想复制按钮中当前的window.location.href
onClick,即使我设置了正确的状态我也无法实际复制它,我的问题是什么?
这里是代码
const [copyHref, setCopyHref] = useState(JSON.stringify(window.location.href));
const copyToClipboard = () => {
setCopyHref(copyHref)
document.execCommand(copyHref);
alert("Copied the text: " + copyHref);
};
<Button onClick={copyToClipboard}/>
当我点击时,我得到了右侧 url
的警报,但它实际上并没有复制它。我该怎么做?
execCommand 函数不是这样工作的。您需要指定要执行的命令,而不是专门用于复制。
详情请参考https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard。
您也可以为此使用本机 js 函数 copy()。
这样试试:
const copyToClipboard = () => {
navigator.clipboard.writeText(copyHref);
alert("Copied the text: " + copyHref);
};
window.location.href
,据我所知,是一个字符串。所以我不太确定 JSON.stringify(window.location.href)
.
你的目标是什么
我也对你使用状态来完成这个基本功能感到困惑。
至于将 URL 复制到剪贴板,我会这样完成:
export default function App() {
const copyToClipboard = () => {
navigator.clipboard.writeText(window.location.href).then(function() {
alert("copied successfully!")
}, function(err) {
alert('Failed to copy');
});
};
return (
<div className="App">
<button onClick={copyToClipboard}> copy </button>
</div>
);
}
我想复制按钮中当前的window.location.href
onClick,即使我设置了正确的状态我也无法实际复制它,我的问题是什么?
这里是代码
const [copyHref, setCopyHref] = useState(JSON.stringify(window.location.href));
const copyToClipboard = () => {
setCopyHref(copyHref)
document.execCommand(copyHref);
alert("Copied the text: " + copyHref);
};
<Button onClick={copyToClipboard}/>
当我点击时,我得到了右侧 url
的警报,但它实际上并没有复制它。我该怎么做?
execCommand 函数不是这样工作的。您需要指定要执行的命令,而不是专门用于复制。 详情请参考https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard。 您也可以为此使用本机 js 函数 copy()。
这样试试:
const copyToClipboard = () => {
navigator.clipboard.writeText(copyHref);
alert("Copied the text: " + copyHref);
};
window.location.href
,据我所知,是一个字符串。所以我不太确定 JSON.stringify(window.location.href)
.
我也对你使用状态来完成这个基本功能感到困惑。
至于将 URL 复制到剪贴板,我会这样完成:
export default function App() {
const copyToClipboard = () => {
navigator.clipboard.writeText(window.location.href).then(function() {
alert("copied successfully!")
}, function(err) {
alert('Failed to copy');
});
};
return (
<div className="App">
<button onClick={copyToClipboard}> copy </button>
</div>
);
}