通过以下方式随时从JavaScript获取ata对象: window.clipboardData
(但是,当您尝试在系统剪切、复制或粘贴事件之外执行此操作时,Internet Explorer将提示用户授予web应用程序剪贴板权限。) 在Chrome中,您可以创建一个Chrome扩展,它将为您提供(这就是我们为Lucidchart所做的)。然后,对于安装了扩展的用户,您只需自己触发系统事件:通过以下方式随时从JavaScript获取ata对象: window.clipboardData,javascript,clipboard,copy-paste,Javascript,Clipboard,Copy Paste,(但是,当您尝试在系统剪切、复制或粘贴事件之外执行此操作时,Internet Explorer将提示用户授予web应用程序剪贴板权限。) 在Chrome中,您可以创建一个Chrome扩展,它将为您提供(这就是我们为Lucidchart所做的)。然后,对于安装了扩展的用户,您只需自己触发系统事件: document.execCommand('copy'); 看起来Firefox已经允许用户向某些站点授予访问剪贴板的权限,但我个人还没有尝试过这些方法。Overview 有三个用于复制到剪贴板的主要
document.execCommand('copy');
看起来Firefox已经允许用户向某些站点授予访问剪贴板的权限,但我个人还没有尝试过这些方法。Overview
有三个用于复制到剪贴板的主要浏览器API:
[navigator.clipboard.writeText]
- 以文本为中心的部分在
- Access是异步的,可以编写,这样安全用户提示(如果显示)就不会中断页面中的JavaScript
- 文本可以直接从变量复制到剪贴板
- 仅在通过HTTPS提供服务的页面上受支持
- 在Chrome 66页面中,非活动选项卡可以在没有权限提示的情况下写入剪贴板
document.execCommand('copy')
- 自2015年4月起,大多数浏览器都支持此功能(请参见下面的浏览器支持)
- 访问是同步的,即停止页面中的JavaScript,直到完成,包括显示和用户与任何安全提示交互
- 文本从DOM中读取并放置在剪贴板上
- 在2015年4月的测试期间,只有Internet Explorer在写入剪贴板时显示权限提示
- 请参阅上的剪贴板API文档
- 允许您通过任何复制事件修改剪贴板上显示的内容,可以包括纯文本以外的其他数据格式
- 这里没有介绍,因为它没有直接回答问题
document.execCommand('copy')
)访问剪贴板。有关详细信息,请参见下文
重要(此处注明2020/02/20)
请注意,由于这篇文章最初是编写的,而其他版本则阻止嵌入式演示“运行代码片段”按钮和“codepen.io示例”在某些浏览器(包括Chrome和Microsoft Edge)中工作
要开发和创建您自己的网页,请通过HTTPS连接提供该网页,以进行测试和开发
下面是一个测试/演示页面,演示了代码的工作原理:
异步+回退
由于浏览器对新的异步剪贴板API的支持级别较高,您可能希望使用document.execCommand('copy')
方法来获得良好的浏览器覆盖率
以下是一个简单的示例(可能无法嵌入此网站,请阅读上面的“重要”注释):
功能fallbackCopyTextToClipboard(文本){
var textArea=document.createElement(“textArea”);
textArea.value=文本;
//避免滚动到底部
textArea.style.top=“0”;
textArea.style.left=“0”;
textArea.style.position=“固定”;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
试一试{
var successful=document.execCommand('copy');
var msg=successful?'successful':'successful';
log('回退:复制文本命令为'+msg');
}捕捉(错误){
console.error('回退:Oops,无法复制',err);
}
document.body.removeChild(textArea);
}
功能copyTextToClipboard(文本){
如果(!navigator.clipboard){
fallbackCopyTextToClipboard(文本);
返回;
}
navigator.clipboard.writeText(text).then(function(){
log('Async:复制到剪贴板成功!');
},函数(err){
console.error('Async:无法复制文本:',err);
});
}
var copyBobBtn=document.querySelector('.js copy bob btn'),
copyJaneBtn=document.querySelector('.js copy-janebtn');
copyBobBtn.addEventListener('click',函数(事件){
copyTextToClipboard(“Bob”);
});
copyJaneBtn.addEventListener('click',函数(事件){
copyTextToClipboard(“Jane”);
});代码>
将剪贴板设置为BOB
将剪贴板设置为JANE
尝试粘贴到此处以查看剪贴板上的内容:
这是其他答案之间的一种组合
var copyToClipboard = function(textToCopy){
$("body")
.append($('<textarea name="fname" class="textToCopyInput"/>' )
.val(textToCopy))
.find(".textToCopyInput")
.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Text copied to clipboard!');
} catch (err) {
window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy);
}
$(".textToCopyInput").remove();
}
当然,你也可以做一些内联样式
.append($('<textarea name="fname" style="opacity: 0; position: absolute;" class="textToCopyInput"/>' )
.append($('')
是一个小型、非Flash的实用程序,允许将文本或HTML数据复制到剪贴板。它非常易于使用,只需包含.js并使用如下内容:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
复制按钮
document.getElementById('markup-copy')。addEventListener('click',function(){
剪贴板。复制({
“文本/纯文本”:“标记文本。将我粘贴到富文本编辑器中。”,
“text/html”:“这里是一些富文本”
}).那么(
函数(){console.log('success');},
函数(err){console.log('failure',err);
});
});
剪贴板.js也处于打开状态
注意:这已被弃用。请迁移到
我使用了clipboard.js
我们可以在npm上获得:
npm install clipboard --save
还有
用法和示例位于。由于Chrome 42+和Firefox 41+现在支持document.execCommand('copy')命令,我使用和的组合创建了两个跨浏览器复制到剪贴板的功能:
功能选择元素内容(el){
//复制文本区域、pre、div等。
if(document.body.createTextRange){
//Internet Explorer
var textRange=document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
textRange.execCommand(“复制”);
function EnybyClipboard() {
this.saveSelection = false;
this.callback = false;
this.pastedText = false;
this.restoreSelection = function() {
if (this.saveSelection) {
window.getSelection().removeAllRanges();
for (var i = 0; i < this.saveSelection.length; i++) {
window.getSelection().addRange(this.saveSelection[i]);
}
this.saveSelection = false;
}
};
this.copyText = function(text) {
var div = $('special_copy');
if (!div) {
div = new Element('pre', {
'id': 'special_copy',
'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
});
div.injectInside(document.body);
}
div.set('text', text);
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
setTimeout(this.restoreSelection.bind(this), 100);
} else return alert('Copy did not work. :(');
};
this.getPastedText = function() {
if (!this.pastedText) alert('Nothing to paste. :(');
return this.pastedText;
};
this.pasteText = function(callback) {
var div = $('special_paste');
if (!div) {
div = new Element('textarea', {
'id': 'special_paste',
'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
});
div.injectInside(document.body);
div.addEvent('keyup', function() {
if (this.callback) {
this.pastedText = $('special_paste').get('value');
this.callback.call(null, this.pastedText);
this.callback = false;
this.pastedText = false;
setTimeout(this.restoreSelection.bind(this), 100);
}
}.bind(this));
}
div.set('value', '');
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
div.focus();
this.callback = callback;
} else return alert('Failed to paste. :(');
};
}
enyby_clip = new EnybyClipboard(); // Init
enyby_clip.copyText('some_text'); // Place this in the Ctrl+C handler and return true;
enyby_clip.pasteText(function callback(pasted_text) {
alert(pasted_text);
}); // Place this in Ctrl+V handler and return true;
<input onclick="this.select();" type='text' value='copy me' />
<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
clip.on( 'noflash', function ( client, args ) {
$("#copy").click(function(){
var txt = $(this).attr('data-clipboard-text');
prompt ("Copy link, then click OK.", txt);
});
});
var copyToClipboard = function(textToCopy){
$("body")
.append($('<textarea name="fname" class="textToCopyInput"/>' )
.val(textToCopy))
.find(".textToCopyInput")
.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Text copied to clipboard!');
} catch (err) {
window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy);
}
$(".textToCopyInput").remove();
}
.textToCopyInput{opacity: 0; position: absolute;}
.append($('<textarea name="fname" style="opacity: 0; position: absolute;" class="textToCopyInput"/>' )
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
npm install clipboard --save
bower install clipboard --save
function appCopyToClipBoard(sText)
{
var oText = false,
bResult = false;
try
{
oText = document.createElement("textarea");
$(oText).addClass('clipboardCopier').val(sText).insertAfter('body').focus();
oText.select();
document.execCommand("Copy");
bResult = true;
}
catch(e) {
}
$(oText).remove();
return bResult;
}
if (!appCopyToClipBoard('Hai there! This is copied to the clipboard.'))
{
alert('Sorry, copy to clipboard failed.');
}
jQuery('#copy').on('click', function () {
copyToClipboard();
});
function copyToClipboard() {
var target = jQuery('#hidden_text');
// Make it visible, so can be focused
target.attr('type', 'text');
target.focus();
// Select all the text
target[0].setSelectionRange(0, target.val().length);
// Copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
}
catch (e) {
succeed = false;
}
// Hide input again
target.attr('type', 'hidden');
return succeed;
}
const copyToClipboard = (function initClipboardText() {
const textarea = document.createElement('textarea');
// Move it off-screen.
textarea.style.cssText = 'position: absolute; left: -99999em';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
return function setClipboardText(text) {
textarea.value = text;
// Check if there is any content selected previously.
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
// iOS Safari blocks programmatic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
}
else {
textarea.select();
}
try {
const result = document.execCommand('copy');
// Restore previous selection.
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return result;
}
catch (err) {
console.error(err);
return false;
}
};
})();
function copy(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
function copy(text) {
var input = document.createElement('textarea');
input.innerHTML = text;
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
(function (text) {
var node = document.createElement('textarea');
var selection = document.getSelection();
node.textContent = text;
document.body.appendChild(node);
selection.removeAllRanges();
node.select();
document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(node);
})('Text To Copy');
function copyToClp(txt){
var m = document;
txt = m.createTextNode(txt);
var w = window;
var b = m.body;
b.appendChild(txt);
if (b.createTextRange) {
var d = b.createTextRange();
d.moveToElementText(txt);
d.select();
m.execCommand('copy');
}
else {
var d = m.createRange();
var g = w.getSelection;
d.selectNodeContents(txt);
g().removeAllRanges();
g().addRange(d);
m.execCommand('copy');
g().removeAllRanges();
}
txt.remove();
}
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
function copytoclipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val('0' + element).select();
document.execCommand("copy");
$temp.remove();
}
<script type="text/javascript">
function copyToClipboard(message) {
var textArea = document.createElement("textarea");
textArea.value = message;
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Unable to copy value , error : ' + err.message);
}
document.body.removeChild(textArea);
}
</script>