Home > Web Front-end > JS Tutorial > body text

Three ways to copy page content with JavaScript (summary sharing)

WBOY
Release: 2022-08-18 17:49:45
forward
2815 people have browsed it

This article brings you relevant knowledge about javascript. It mainly introduces you to the detailed explanation of three methods of copying page content using JS. Friends in need can refer to it. I hope it can Helps.

Three ways to copy page content with JavaScript (summary sharing)

[Related recommendations: javascript video tutorial, web front-end]

There are many third-party plug-ins now The copy function can be implemented, but if we are asked to do it ourselves, do we know how to implement it?

This article introduces three implementation solutions.

Method 1: Async Clipboard API

Use Async Clipboard API

This method is the easiest to use, but the compatibility is not very good and there are many requirements.

Sample code:

const promise = navigator.clipboard.writeText(newClipText);
Copy after login

It should be noted that the return value of the method is a Promise. And when using this method, the page must be in focus state, otherwise an error will be reported.

Method 2: Document.execCommand API

Use Document.execCommand

Although this method is warned to be abandoned and no longer belongs to the web standard, it has many historical factors. I believe that browsing The device will be supported for a long time.

Copy DOM element content

<p id="content">123456</p>
<button id="copyButton">复制</button>
Copy after login

When copying DOM elements, you need to use the selection API and Range API additionally.

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

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

Sample code:

const copyButton = document.getElementById(&#39;copyButton&#39;);
const content = document.getElementById(&#39;content&#39;);
copyButton.addEventListener(&#39;click&#39;, function () {
  const selection = window.getSelection();
  const range = document.createRange();
  // 设置选中内容
  range.selectNodeContents(content);
  // 清空选中内容
  selection.removeAllRanges();
  // 添加选中内容
  selection.addRange(range);
  document.execCommand(&#39;copy&#39;);
});
Copy after login

selection needs to be cleared first and then added to the range.

There will be a detail issue here. After clicking the copy button, the copied content is selected, which is a bit abrupt.

The solution is to call selection.removeAllRanges() after copying is completed to clear the selection.

Consider another situation where the user selects part of the page before copying. After the copy is completed, in addition to clearing the selected copy content, you also need to restore the content that the user selected before copying.

The implementation code is as follows:

const copyButton = document.getElementById(&#39;copyButton&#39;);
const content = document.getElementById(&#39;content&#39;);
copyButton.addEventListener(&#39;click&#39;, function () {
  const selection = window.getSelection();
  const range = document.createRange();
  // 缓存用户选中的内容
  const currentRange =
    selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  // 设置文档片段
  range.selectNodeContents(content);
  // 清空选中内容
  selection.removeAllRanges();
  // 将文档片段设置为选中内容
  selection.addRange(range);
  try {
    // 复制到剪贴板
    document.execCommand(&#39;copy&#39;);
  } catch (err) {
    // 提示复制失败
  } finally {
    selection.removeAllRanges();
    if (currentRange) {
      // 还原用户选中内容
      selection.addRange(currentRange);
    }
  }
});
Copy after login

First cache the content selected by the user, and then restore it after the copy is completed.

Copy the content of the input element

Use the select method of the input element object to select the content without creating a range fragment to set the selected content.

Sample code:

const copyButton = document.getElementById(&#39;copyButton&#39;);
const inputEl = document.getElementById(&#39;input&#39;);
copyButton.addEventListener(&#39;click&#39;, function () {
  const selection = window.getSelection();
  const currentRange =
    selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  // 选中 input 内容
  inputEl.select();
  // 复制到剪贴板
  try {
    document.execCommand(&#39;copy&#39;);
  } catch (err) {
    // 提示复制失败
    // 。。。
  } finally {
    selection.removeAllRanges();
    if (currentRange) {
      // 还原用户选中内容
      selection.addRange(currentRange);
    }
  }
});
Copy after login

Clicking the copy button will also not remove the previously selected content.

Method 3: Overwrite the copy event

w3c.github.io/clipboard-a…

Quote a piece of code in the above link as an example:

// Overwrite what is being copied to the clipboard.
document.addEventListener(&#39;copy&#39;, function (e) {
  // e.clipboardData is initially empty, but we can set it to the
  // data that we want copied onto the clipboard.
  e.clipboardData.setData(&#39;text/plain&#39;, &#39;西炒蛋&#39;);
  // This is necessary to prevent the current document selection from
  // being written to the clipboard.
  e.preventDefault();
});
Copy after login

Copy any content on the page and paste the output content will be "Western scrambled eggs".

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Three ways to copy page content with JavaScript (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template