将当前网址复制到剪贴板 [英] Copy current URL to clipboard

查看:336
本文介绍了将当前网址复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定今天为什么对我来说如此困难,但是由于某种原因,我似乎无法将其复制到剪贴板。总体而言,我正在寻找一种无需创建某些隐藏文本元素的方法

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 without needing to create some hidden text elements.

这就是我正在尝试的方法到目前为止:

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;
});

当我尝试使用 .select()进行操作时code>我得到这个错误:
t.select不是一个函数
所以我不确定100%是最好的方法去解决这个问题。同样,无需使用jQuery(或任何其他JS库),也无需使用某种隐藏的文本字段。

When I try to go about it using the .select() I get this error: t.select is not a function So 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.

推荐答案

临时的DOM元素来保存URL



不幸的是,没有用于剪贴板操作的标准API,所以我们剩下的使用HTML input 元素来满足我们的需求。这个想法是创建一个输入,将其值设置为当前文档的URL,选择其内容并执行 copy

You can create a temporary DOM element to hold the URL

Unfortunately there is no standard API for clipboard operations, so we're left with the hacky way of using a HTML input element 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.

然后我们清理混乱,而不是将输入设置为隐藏并污染DOM。

We then clean up the mess instead of setting input to hidden and polluting the 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);

这篇关于将当前网址复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆