Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

javascript - paste data from clipboard using document.execCommand("paste"); within firefox extension

I am trying to paste clipboard data into a variable that gets fed into and fired via XMLhttprequest POST message.

I have created a firefox user.js with this code to increase access to clipboard based on this recommendation.

user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.sites", "mydomain");
user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess");
user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess");

Do I need to change "mydomain" in line two? I do not want any sites to have access. Just my internal firefox extension.

I have read several guides here and here as well as mozilla.

Here is the code I have so far. The clipboard contents should get sent POST method via XMLHttpRequest. XMLHttpRequest works, as I have been using it for other variables.

 var pastetext = document.execCommand('paste');
 var req = new XMLHttpRequest();
 req.open('POST', pastetext, true);
 req.onreadystatechange = function(aEvt) {
     if (req.readyState == 4) {
         if (req.status == 200)
             dump(req.responseText);
         else
             dump("Error loading page
");
     }
 };
 req.send(null);

I am grateful for any help. Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need is not the execCommand but you need to read the data from the clipboard. Your addon is in privelaged scope so you don't need to worry about those preferences. (user.js is firefox-addon right?)

See here:

This way you can read the contents into the var pastedContents.

Here is your example with the above worked in:

var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
trans.addDataFlavor("text/unicode");
Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard);
var pastetextNsiSupports = {};
var pastetextNsiSupportsLength = {};
trans.getTransferData("text/unicode", pastetextNsiSupports, pastetextNsiSupportsLength);

var pastetext = pastetextNsiSupports.value.QueryInterface(Ci.nsISupportsString).data;
 var req = new XMLHttpRequest();
 req.open('POST', pastetext, true);
 req.onreadystatechange = function(aEvt) {
     if (req.readyState == 4) {
         if (req.status == 200)
             dump(req.responseText);
         else
             dump("Error loading page
");
     }
 };
 req.send(null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...