javascript 将当前 URL 复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49618618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy current URL to clipboard
提问by ultraloveninja
Not sure why this has been so difficult for me today, but for some reason I cannot seem to get it to copy the current URL to the clipboard. Overall, I'm looking for a way to do it withoutneeding to create some hidden text elements.
不知道为什么今天这对我来说如此困难,但由于某种原因,我似乎无法将当前 URL 复制到剪贴板。总的来说,我正在寻找一种无需创建一些隐藏文本元素的方法。
This is what I'm trying so far:
这是我到目前为止正在尝试的:
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;
});
When I try to go about it using the .select()I get this error:
t.select is not a functionSo I'm not 100% sure what the best way to go about this. Again, without using jQuery (or any other JS library) and not using some sort of hidden textfield.
当我尝试使用它来.select()解决这个问题时,我得到了这个错误:
t.select is not a function所以我不是 100% 确定解决这个问题的最佳方法是什么。同样,不使用 jQuery(或任何其他 JS 库)也不使用某种隐藏的文本字段。
回答by ppajer
You can create a temporary DOM element to hold the URL
您可以创建一个临时 DOM 元素来保存 URL
Unfortunately there is no standard API for clipboard operations, so we're left with the hacky way of using a HTML inputelement to fit our needs. The idea is to create an input, set its value to the URL of the current document, select its contents and execute copy.
不幸的是,没有用于剪贴板操作的标准 API,因此我们只能使用 HTMLinput元素来满足我们的需要。这个想法是创建一个输入,将其值设置为当前文档的 URL,选择其内容并执行copy.
We then clean up the mess instead of setting input to hidden and polluting the DOM.
然后我们清理混乱而不是将输入设置为隐藏和污染 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);

