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.
[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.
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);
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.
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.
<p id="content">123456</p> <button id="copyButton">复制</button>
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('copyButton'); const content = document.getElementById('content'); copyButton.addEventListener('click', function () { const selection = window.getSelection(); const range = document.createRange(); // 设置选中内容 range.selectNodeContents(content); // 清空选中内容 selection.removeAllRanges(); // 添加选中内容 selection.addRange(range); document.execCommand('copy'); });
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('copyButton'); const content = document.getElementById('content'); copyButton.addEventListener('click', 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('copy'); } catch (err) { // 提示复制失败 } finally { selection.removeAllRanges(); if (currentRange) { // 还原用户选中内容 selection.addRange(currentRange); } } });
First cache the content selected by the user, and then restore it after the copy is completed.
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('copyButton'); const inputEl = document.getElementById('input'); copyButton.addEventListener('click', function () { const selection = window.getSelection(); const currentRange = selection.rangeCount === 0 ? null : selection.getRangeAt(0); // 选中 input 内容 inputEl.select(); // 复制到剪贴板 try { document.execCommand('copy'); } catch (err) { // 提示复制失败 // 。。。 } finally { selection.removeAllRanges(); if (currentRange) { // 还原用户选中内容 selection.addRange(currentRange); } } });
Clicking the copy button will also not remove the previously selected content.
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('copy', 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('text/plain', '西炒蛋'); // This is necessary to prevent the current document selection from // being written to the clipboard. e.preventDefault(); });
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!