复制到剪贴板的所有浏览器使用javascript
Copy to Clipboard for all Browsers using javascript
我试图使"复制到剪贴板"在所有浏览器上都能工作,但没有运气。
我正在使用javascript,我不想使用Zero剪贴板。
请让我们知道我的代码有什么问题。
谢谢你的帮助。
下面是代码(目前我的代码只在IE浏览器上工作):-
<script type="text/javascript">
function copyToClipboard(s)
{
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
var copytext=meintext;
str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
</script>
<textarea id='testText' rows="10" cols="100">Enter your Sample text</textarea><br />
<button onclick="copyToClipboard(document.getElementById('testText').value);" >clipboard</button><br /><br />
<textarea rows="10" cols="100">Paste your text here</textarea><br />
这适用于firefox 3.6。x和IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
我也花了很多时间寻找这个问题的解决方案。以下是我到目前为止发现的:
如果你想让你的用户能够点击按钮并复制一些文本,你可能必须使用Flash。
如果你想让你的用户在页面的任何地方按Ctrl+C,但总是复制xyz到剪贴板,我在YUI3中写了一个全JS的解决方案(尽管它可以很容易地移植到其他框架,或者原始JS,如果你感觉特别自我厌恶)。
它涉及在屏幕上创建一个文本框,当用户按Ctrl/CMD时,该文本框会被高亮显示。当他们按下"C"键后,他们复制隐藏的文本。如果它们点击了'V',它们会在粘贴事件触发之前被重定向到一个容器(你选择的)。
这个方法可以很好地工作,因为当你在body的任何地方监听Ctrl/CMD按键时,'A', 'C'或'V'按键监听器只附加到隐藏的文本框(而不是整个body)。它也不需要打破用户的期望——只有当你没有选择要复制的内容时,你才会被重定向到隐藏框!
这是我在我的网站工作,但检查http://at.cg/js/clipboard.js更新,如果有任何:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.'n 'nYou do not need to select things manually - just press Ctrl+C! 'n 'n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
出于安全原因,大多数浏览器不允许修改剪贴板(当然IE除外…)。
使复制到剪贴板功能跨浏览器兼容的唯一方法是使用Flash。
我觉得zeroclipboard很棒。此版本适用于最新的Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
- 如何知道浏览器javascript的名称
- 跨浏览器javascript下载功能
- 如何避免在浏览器 JavaScript 中双击时(单击鼠标)处理
- 有没有办法从浏览器javascript打开Windows 10上的Microsoft地图
- 如何从应用程序的服务器端向浏览器 JavaScript 发送事件
- 浏览器Javascript - 任何了解用户当前IP的方法
- 如何强制浏览器/javascript 清除/忽略缓存文件
- 在浏览器 (javascript) 中将 Cognito 凭证与 AWS 配合使用时,不断收到“缺少凭证”错误
- 读取使用浏览器 Javascript 忽略的文件
- 如何在浏览器 JavaScript 中维护来自同一站点的不同页面加载的状态
- 跨浏览器JavaScript,用于从用户的选择中获取和替换确切的HTML
- 在关闭浏览器 javascript 时删除本地存储
- 如何在android浏览器javascript中捕获退格键代码
- 使用JavaScript启用和禁用浏览器JavaScript选项
- 浏览器Javascript:setTimeout和主程序
- 了解开发者控制台在当前浏览器(JavaScript)中是否处于活动状态
- 是否可以验证浏览器Javascript会话的完整性
- 我们可以期待一个浏览器javascript API到DNS解析程序
- node.js和浏览器javascript的配置相同
- 使用浏览器JavaScript SDK检查AWS S3上是否存在文件