简体   繁体   English

Javascript 使用导航器将 url 链接复制到剪贴板

[英]Javascript copy url link to clipboard using navigator

I am trying to copy url link using below code我正在尝试使用以下代码复制 url 链接

let text = 'click here'
let hrefLink = `<a href="https://stackoverflow.com">${text}</a>`;

if (navigator && navigator.clipboard != undefined) {
  navigator.clipboard.writeText(hrefLink);
}

If I am using above code the pasted text will be link like如果我使用上面的代码,粘贴的文本将是链接

" <a href="https://stackoverflow.com">click here</a> " " <a href="https://stackoverflow.com">click here</a> "

But I am trying to paste the text like this " click here " I can see some examples using document.exec() .但我试图粘贴这样的文本“单击此处”我可以看到一些使用document.exec()示例。 If somebody suggest using navigator.clipboard it will be helpful如果有人建议使用navigator.clipboard它会有所帮助

Your example tries to copy to the clipboard using navigator.clipboard.writeText , which is only capable of writing plain text.您的示例尝试使用navigator.clipboard.writeText复制到剪贴板,它只能写入纯文本。 If you'd like to embed a link, you may want to try writing HTML instead, via navigator.clipboard.write , and the 'text/html' type.如果您想嵌入链接,您可能想尝试通过navigator.clipboard.write'text/html'类型编写 HTML。

For an example of how to write HTML using the Clipboard API, see this Safari blog post example, or the source of this HTML demo site .有关如何使用剪贴板 API 编写 HTML 的示例,请参阅此Safari 博客文章示例,或此HTML 演示站点的源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM