search
HomeWeb Front-endJS TutorialHow to copy content to clipboard in JS

How to copy content to clipboard in JS

Apr 12, 2018 pm 03:54 PM
javascriptcontentclipboard

This time I will show you how to copy content to the clipboard with JS. What are the precautions for copying content to the clipboard with JS? The following is a practical case. Get up and take a look.

Common methods

After checking the all-powerful Google, the common methods now are mainly the following two:

Third-party library: clipboard.js

Native method:
document.execCommand()

Let’s take a look at how these two methods are used.

clipboard.js

This is the official website of clipboard:

https://clipboardjs.com/, it seems so simple.

Quote

Direct quote:

Package:

npm install clipboard --save , then import Clipboard from 'clipboard';

use

Copy from input box

Now there is an <input> tag on the page, we need to copy the content inside it, we can do this:

<input>
<button>点我复制</button>
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
Notice that a

data-clipboard-target attribute is added to the

Copy directly

Sometimes, we don't want to copy the content from <input>, but just get the value directly from the variable. If in Vue we could do this:

import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';

event

Sometimes we need to do something after copying, in which case we need the support of

callback function.

Add the following code to the processing function:

// 复制成功后执行的回调函数
clipboard.on('success', function(e) {
 console.info('Action:', e.action); // 动作名称,比如:Action: copy
 console.info('Text:', e.text); // 内容,比如:Text:hello word
 console.info('Trigger:', e.trigger); // 触发元素:比如:<button>点我复制</button>
 e.clearSelection(); // 清除选中内容
});
// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
 console.error('Action:', e.action);
 console.error('Trigger:', e.trigger);
});

Summary

The document also mentions that if

clipboard is used in a single page, in order to make lifecycle management more elegant, remember btn.destroy() ## after use. #Destroy it. Isn’t clipboard very simple to use? However, is it not elegant enough to use additional third-party libraries just for a copy function? What should we do at this time? Then use native methods to achieve it.

document.execCommand() method

Let’s first look at how this method is defined on

MDN

:

which allows one to run commands to manipulate the contents of the editable region.

This means that commands can be run to manipulate the contents of the editable area. Note that it is an editable area.

Definition

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

The method returns a Boolean value indicating whether the operation was successful.

    aCommandName: Indicates the command name, such as: copy, cut, etc. (see commands for more commands);
  • aShowDefaultUI: Whether to display the user interface, usually false;
  • <p></p>aValueArgument: Some commands require additional parameters, which are generally not used;
  • <p></p>
compatibility

The compatibility of this method was actually not very good before, but fortunately it is now basically compatible with all mainstream browsers and can also be used on mobile terminals.

use

从输入框复制
现在页面上有一个 <input> 标签,我们想要复制其中的内容,我们可以这样做:

<input>
<button>点我复制</button>

js代码

const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
	const input = document.querySelector('#demoInput');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
})

其它地方复制

有的时候页面上并没有 <input> 标签,我们可能需要从一个 <p></p> 中复制内容,或者直接复制变量。

还记得在 execCommand() 方法的定义中提到,它只能操作可编辑区域,也就是意味着除了 <input>、

这时候我们需要曲线救国。

js代码

const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
	const input = document.createElement('input');
	document.body.appendChild(input);
 	input.setAttribute('value', '听说你想复制我');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
 document.body.removeChild(input);
})

算是曲线救国成功了吧。在使用这个方法时,遇到了几个坑。

遇到的坑

在Chrome下调试的时候,这个方法时完美运行的。然后到了移动端调试的时候,坑就出来了。

对,没错,就是你,ios。。。

1、点击复制时屏幕下方会出现白屏抖动,仔细看是拉起键盘又瞬间收起

知道了抖动是由于什么产生的就比较好解决了。既然是拉起键盘,那就是聚焦到了输入域,那只要让输入域不可输入就好了,在代码中添加 input.setAttribute('readonly', 'readonly'); 使这个 <input> 是只读的,就不会拉起键盘了。

2、无法复制

这个问题是由于 input.select() 在ios下并没有选中全部内容,我们需要使用另一个方法来选中内容,这个方法就是 input.setSelectionRange(0, input.value.length);。

完整代码如下:

const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
	const input = document.createElement('input');
 input.setAttribute('readonly', 'readonly');
 input.setAttribute('value', 'hello world');
 document.body.appendChild(input);
	input.setSelectionRange(0, 9999);
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
 document.body.removeChild(input);
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

angularjs中获取单选按钮的方法

脚本加载后执行JS回调函数的方法

The above is the detailed content of How to copy content to clipboard in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software