未加星标

Quick Tip: Accessing The Clipboard With JavaScript

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

In this article we’re going to show you how to use simple vanilla javascript snippets to:

Add text to the clipboard on user action, such as the press of a button. Modify the content of the clipboard when a user copies something.

The APIs we will be using don’t require any external libraries, and have almost perfect browser compatibility!

Copy On Click

An awesome accessibility feature you can add to your website is the ability to copy strings directly via button press. This interaction can be applied toquickly grab URLs, long strings such as SSH keys, terminal commands, hex colors, or any other data that is frequently copy & pasted.

To make this happen we will need to use a cool JavaScript method called execCommand() . It allows us to invoke a number of different events that manipulate editable content such as making text bold/italic, doing undo/redo, and also copy/cut/paste.

document.execCommand('copy');

This works exactly like pressing CTRL/Cmd+C on your keyboard, so in order to copy any textwe firstneed to have itselected. This is possible in JavaScript thanks to the Selection API , which allows us to programatically make a text selection from any HTML element on the page.

var button = document.getElementById("copy-button"),
contentHolder = document.getElementById("content-holder");
button.addEventListener("click", function() {
// We will need a range object and a selection.
var range = document.createRange(),
selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
// Make the range select the entire content of the contentHolder paragraph.
range.selectNodeContents(contentHolder);
// Add that range to the selection.
selection.addRange(range);
// Copy the selection to clipboard.
document.execCommand('copy');
// Clear selection if you want to.
selection.removeAllRanges();
}, false);

To see the example in action check out the editor below:

var button = document.getElementById("copy-button"),
contentHolder = document.getElementById("content-holder");
button.addEventListener("click", function() {
// We will need a range object and a selection.
var range = document.createRange(),
selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
// Make the range select the entire content of the contentHolder paragraph.
range.selectNodeContents(contentHolder);
// Add that range to the selection.
selection.addRange(range);
// Copy the selection to clipboard.
document.execCommand('copy');
// Clear selection if you want to.
selection.removeAllRanges();
}, false); <p id="content-holder">This text will be inserted into the clipboard.</p>
<button id="copy-button">Copy Text</button>
<textarea></textarea> *{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
padding: 20px;
font: normal 16px sans-serif;
color: #555;
}
p{
margin-bottom: 20px;
}
button{
padding: 8px 12px;
margin-bottom: 20px;
}
textarea {
display: block;
padding: 10px;
width: 400px;
height: 120px;
}

In the example above the content we want to copy is simply stored in a paragraph. If the text you need is not on the page, you will need to first write it in an element hidden off-screen.

Modify Copied Text

Here we will show you how to manipulate content in the clipboard after it’s been copied. This can be very useful for escaping code, formatting numbers and dates, or for other text transformations such as uppercase, lowercase, etc.

JavaScript provides us with copy() and paste() events, but they are designed in such a way that the content stored in the clipboard is secure:

In the copy event handler we cannot read what’s stored in clipboard, as there may be personal info which we shouldn’t have access to. We can, however, overwrite the clipboard data. In the paste event it’s the opposite: we can read the data, but we cannot change it.

Since we want to read and write at the same time, we will need to use the Selection API once more. Here is the solution:

document.addEventListener('copy', function(e){
// We need to prevent the default copy functionality,
// otherwise it would just copy the selection as usual.
e.preventDefault();
// The copy event doesn't give us access to the clipboard data,
// so we need to get the user selection via the Selection API.
var selection = window.getSelection().toString();
// Transform the selection in any way we want.
// In this example we will escape HTML code.
var escaped = escapeHTML(selection);
// Place the transformed text in the clipboard.
e.clipboardData.setData('text/plain', escaped);
});

You can try the code in the editor below:

document.addEventListener('copy', function(e){
// We need to prevent the default copy functionality,
// otherwise it would just copy the selection as usual.
e.preventDefault();
// The copy event doesn't give us access to the clipboard data,
// so we need to get the user selection via the Selection API.
var selection = window.getSelection().toString();
// Transform the selection in any way we want.
var escaped = escapeHtml(selection);
// Place the transformed text in the clipboard.
e.clipboardData.setData('text/plain', escaped);
});
// Primitive HTML escape function.
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
} <p class="copy-text">Copy and paste any of the HTML code below to escape it.</p>
<pre><code>
<div class="container">
<div class="starter-template">
<h1>Lorem Ipsum</h1>
<p class="lead">Lorem ipsum dolor sit amet.</p>
</div>
</div>
</code></pre>
<textarea class="paste-text"></textarea> *{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
padding: 20px;
font: normal 16px sans-serif;
color: #555;
}
pre{
font-size: 14px;
margin-bottom: 20px;
}
textarea {
padding: 10px;
width: 500px;
height: 170px;
} Further Reading

In this quick tip we presented you two usefulsnippets for working with the clipboard in pure vanilla JavaScript. We used a bunch of hip native APIs, so here they are again if you want to read more about them:

execCommand Execute actions such as copy, paste, cut, bold, italic, underline, delete, and many others. MDN , C

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaJavaScriptHTML
分页:12
转载请注明
本文标题:Quick Tip: Accessing The Clipboard With JavaScript
本站链接:http://www.codesec.net/view/480692.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(30)