[英]Copy current URL to clipboard
不知道为什么今天这对我来说如此困难,但由于某种原因,我似乎无法将当前 URL 复制到剪贴板。 总的来说,我正在寻找一种不需要创建一些隐藏文本元素的方法。
到目前为止,这是我正在尝试的:
var shareBtn = document.querySelector(".share-button");
shareBtn.addEventListener('click', function(event) {
var cpLink = window.location.href;
cpLink.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
event.preventDefault;
});
当我尝试使用.select()
此操作时,出现此错误: t.select is not a function
所以我不能 100% 确定解决此问题的最佳方法。 同样,不使用 jQuery(或任何其他 JS 库)并且不使用某种隐藏的文本字段。
不幸的是,没有用于剪贴板操作的标准 API,所以我们只能使用 HTML input
元素来满足我们的需求。 这个想法是创建一个输入,将其值设置为当前文档的 URL,选择其内容并执行copy
。
然后我们清理混乱,而不是将输入设置为隐藏并污染 DOM。
var dummy = document.createElement('input'),
text = window.location.href;
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
2021 年更新:您可以像这样使用 剪贴板 API :
navigator.clipboard.writeText(window.location.href);
当浏览器处理复制时, ppajer 的答案确实是所有需要的,而不涉及对剪贴板事件的任何自定义处理。
但是,如果您或某些库挂钩到复制事件(例如window.addEventListener('copy', ...)
,然后如果该处理程序依赖于使用window.getSelection()
,那么一个 19 岁的Firefox 问题会咬你. 就像MDN 说的:
值得注意的是,目前
getSelection()
不适用于 Firefox、Edge(旧版)和 Internet Explorer 中的<textarea>
和<input>
元素的内容。
因此, getSelection()
在HTMLInputElement#select
之后返回非空结果,但不提供实际选择的内容。 通过使用非输入元素临时保存 URL 可以轻松修复:
function copyUrl() {
if (!window.getSelection) {
alert('Please copy the URL from the location bar.');
return;
}
const dummy = document.createElement('p');
dummy.textContent = window.location.href;
document.body.appendChild(dummy);
const range = document.createRange();
range.setStartBefore(dummy);
range.setEndAfter(dummy);
const selection = window.getSelection();
// First clear, in case the user already selected some other text
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
document.body.removeChild(dummy);
}
(当没有自定义处理程序挂钩到复制事件时,上述内容也将起作用。)
window.navigator.clipboard.writeText(textToCopy);
var $temp = $("<input>");
var $url = $('.copy').attr('href');
$('.clipboard').on('click', function() {
$("body").append($temp);
$temp.val($url).select();
document.execCommand("copy");
$temp.remove();
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'URL copied! '
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.