views:

240

answers:

1

I'm trying to create a read from clipboard javascript function, and it's generally working, but I can't seem to extract the actual string from the object I create with the out parameter (Components.interfaces.nsITransferable). In case you're wondering, this is for a local intranet, and I have enabled clipboard access.

This is the part of the code where I create objects for the out parameters, and then set them. I know it's basically working, because if I return obj_length.value it gives me the right length (*2 for unicode). However, obj.value only gives me an object of type [xpconnect wrapped nsISupports]. I need the string with the clipboard contents!

var obj = {};
var obj_length = {};
b.getTransferData("text/unicode", obj, obj_length);
return obj.value;

Can anyone please help me figure out how to extract the clipboard contents? I'm so close!

A: 

As it turns out, I was able to answer my own question. It's a bit of RTFM to me, but in case it's helpful for other people to find it here on SO, here's where I found it:

https://developer.mozilla.org/en/Using_the_Clipboard

And here is the complete code I used. It's tested and working in FF 3.5. It won't work in IE, but it should be pretty trivial to test for IE and add support for that browser. Not so sure about Chrome, Opera, Safari, etc. Please recall that you have to enable clipboard access in Firefox, or it won't work. Therefore, it's probably not suitable for public sites:

try {
 netscape.security.PrivilegeManager
   .enablePrivilege("UniversalXPConnect");
} catch (e) {
 alert("You need to enable clipboard access in FireFox");
 return false;
}

var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
if (!clip) return false;

var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return false;
trans.addDataFlavor("text/unicode");

clip.getData(trans, clip.kGlobalClipboard);

var str       = new Object();
var strLength = new Object();

trans.getTransferData("text/unicode", str, strLength);

if (str) str       = str.value.QueryInterface(Components.interfaces.nsISupportsString);
if (str) pastetext = str.data.substring(0, strLength.value / 2);

return pastetext;
M3Mania