我真的需要在Firefox中将某些文本复制到操作系统剪贴板中。
我知道在IE中很容易实现,但在Chrome和Opera中除非使用Flash否则不可能。由于不同原因,我无法使用Flash解决方案!
过去曾经有解决方法,但现在我发现netscape.security.PrivilegeManager.enablePrivilege被保护了(自版本17以来)。
根据这篇文章,看起来仍然有可能:
https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
我认为还需要像这样在user.js文件中启用该功能:
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.sites", "http://");
user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess");
但我该怎么做呢?经过一些尝试并没有取得很大的成功,我认为网上也没有通俗易懂的指南来解释如何以通用的方式实现它。例如,关于如何启用JavaScript访问剪贴板的简单指南。希望还有一份能够供初学者使用的指南。我想要做到它并在这里发布,但首先需要一个可行的解决方案。
根据网络上的信息,复制到剪贴板有两种解决方案;
document.execCommand("copy", false, null)
和
var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
gClipboardHelper.copyString("Put me on the clipboard, please.");
两者在我第一次尝试时都失败了。
下面的解决方案需要用户按下CTRL+C,而我需要一种只需按下按钮(页面上的多个按钮)即可复制文本的解决方案。
https://dev59.com/zVLTa4cB1Zd3GeqPZ15y#11346026
我的旧解决方案是这样的:
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if(clip)
{
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if(trans)
{
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if(str)
{
var clipid=Components.interfaces.nsIClipboard;
if(clipid)
{
str.data = cliptext;
trans.addDataFlavor('text/unicode');
trans.setTransferData("text/unicode", str, cliptext.length*2);
clip.setData(trans, null, clipid.kGlobalClipboard); // No return value
return 0;
}
}
}
}
在非特权代码中(不是插件等),Components.classes未定义,因此我认为任何使用此的解决方案都不再起作用。一个选择是制作一个将在特权代码区域执行并将文本发送到此插件以处理复制到操作系统剪贴板的插件(不错的新项目)。
这只留下document.execCommand("copy", false, null)单独作为解决方案。
尝试了这段代码,它没有复制任何内容到操作系统剪贴板 - 但是没有生成任何错误。
var pre = document.getElementById('pcryptcopytext');
if(!pre)
{
pre = document.createElement("pre");
pre.setAttribute('id', 'pcryptcopytext');
pre.setAttribute('style', 'opacity: 0; position: absolute; top: -10000px; right: 0;');
document.body.appendChild(pre);
}
pre.innerHTML = cliptext;
pre.contentEditable = true;
//pre.unselectable = "off";
//pre.focus();
if (document.createRange)
{
var rng = document.createRange();
rng.selectNodeContents(pre);
document.execCommand("copy", false, null);
document.body.removeChild(pre);
}
那么,有人有可行的解决方案吗?