JavaScript复制页面内容的三种方案(总结分享)

 2435

本篇文章给大家带来了关于javascript的相关知识,主要为大家介绍了使用 JS 复制页面内容的三种方案详解,有需要的朋友可以借鉴参考下,希望能够有所帮助。


JavaScript复制页面内容的三种方案(总结分享)


现在有很多第三方插件能够实现 copy 功能,但如果让我们自己去做,我们知道如何去实现吗?

这篇文章介绍三种实现方案。


方式一:Async Clipboard API

使用 Async Clipboard API

这种方式使用起来最简单,但兼容性不太好,而且要求比较多。


JavaScript复制页面内容的三种方案(总结分享)


示例代码:

const promise = navigator.clipboard.writeText(newClipText);

需要注意,方法的返回值是个 Promise。并且使用此方法时,页面必须处于 focus 状态,否则会报错。


方式二:Document.execCommand API

使用 Document.execCommand

此方法虽然警告被废弃,不再属于 web 标准,但历史因素较多,相信浏览器还会支持很久。


JavaScript复制页面内容的三种方案(总结分享)


复制 DOM 元素内容

  1. <p id="content">123456</p>
  2. <button id="copyButton">复制</button>

复制 DOM 元素的时候,需要额外使用到 selection API 和 Range API。

developer.mozilla.org/en-US/docs/…

developer.mozilla.org/en-US/docs/…

示例代码:

  1. const copyButton = document.getElementById('copyButton');
  2. const content = document.getElementById('content');
  3. copyButton.addEventListener('click', function () {
  4.   const selection = window.getSelection();
  5.   const range = document.createRange();
  6.   // 设置选中内容
  7.   range.selectNodeContents(content);
  8.   // 清空选中内容
  9.   selection.removeAllRanges();
  10.   // 添加选中内容
  11.   selection.addRange(range);
  12.   document.execCommand('copy');
  13. });

selection 需要先清空再添加 range。

这里会有一个细节问题,点击复制按钮之后,被复制的内容处于选中状态,有些突兀。

解决方式是在复制完成之后调用 selection.removeAllRanges() 清空选中内容即可。

再考虑一种情况,用户在复制之前就选中了页面的部分内容。在复制完成之后,除了清空选中的复制内容,还需要还原用户在复制之前就选中的内容。

实现代码如下:

  1. const copyButton = document.getElementById('copyButton');
  2. const content = document.getElementById('content');
  3. copyButton.addEventListener('click', function () {
  4.   const selection = window.getSelection();
  5.   const range = document.createRange();
  6.   // 缓存用户选中的内容
  7.   const currentRange =
  8.     selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  9.   // 设置文档片段
  10.   range.selectNodeContents(content);
  11.   // 清空选中内容
  12.   selection.removeAllRanges();
  13.   // 将文档片段设置为选中内容
  14.   selection.addRange(range);
  15.   try {
  16.     // 复制到剪贴板
  17.     document.execCommand('copy');
  18.   } catch (err) {
  19.     // 提示复制失败
  20.   } finally {
  21.     selection.removeAllRanges();
  22.     if (currentRange) {
  23.       // 还原用户选中内容
  24.       selection.addRange(currentRange);
  25.     }
  26.   }
  27. });

先缓存用户选中的内容,复制完成之后,再还原。


复制 input 元素内容

使用 input 元素对象的 select 方法即可选中内容,无需创建 range 片段设置选中内容。

示例代码:

  1. const copyButton = document.getElementById('copyButton');
  2. const inputEl = document.getElementById('input');
  3. copyButton.addEventListener('click', function () {
  4.   const selection = window.getSelection();
  5.   const currentRange =
  6.     selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  7.   // 选中 input 内容
  8.   inputEl.select();
  9.   // 复制到剪贴板
  10.   try {
  11.     document.execCommand('copy');
  12.   } catch (err) {
  13.     // 提示复制失败
  14.     // 。。。
  15.   } finally {
  16.     selection.removeAllRanges();
  17.     if (currentRange) {
  18.       // 还原用户选中内容
  19.       selection.addRange(currentRange);
  20.     }
  21.   }
  22. });

点击复制按钮,同样不会移除之前选中的内容。


方法三:覆写 copy 事件

w3c.github.io/clipboard-a…

引用上面链接内的一段代码作为示例:

  1. // Overwrite what is being copied to the clipboard.
  2. document.addEventListener('copy', function (e) {
  3.   // e.clipboardData is initially empty, but we can set it to the
  4.   // data that we want copied onto the clipboard.
  5.   e.clipboardData.setData('text/plain', '西炒蛋');
  6.   // This is necessary to prevent the current document selection from
  7.   // being written to the clipboard.
  8.   e.preventDefault();
  9. });

在页面复制任何内容,粘贴输出的内容都会是 “西炒蛋”。


TAG标签:
本文网址:https://www.zztuku.com/detail-12979.html
站长图库 - JavaScript复制页面内容的三种方案(总结分享)
申明:本文转载于《脚本之家》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐

    免费商用字体-荆南俊俊体