How to copy data to the clipboard with Greasemonkey?

LA_ picture LA_ · Oct 25, 2012 · Viewed 11.5k times · Source

I found this question but trying to use the code given there:

unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
    .getService(Components.interfaces.nsIClipboardHelper)
;
clipboardHelper.copyString('test');


Gives the error message:

A script from «http://example.com» was denied UniversalXPConnect privileges.



I also tried to use (from Mozilla site):

const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
    .getService(Components.interfaces.nsIClipboardHelper)
;
gClipboardHelper.copyString("test2");

Which gives the error message: Components.classes is undefined.

In both cases it doesn't work with the latest Firefox on Windows 7.
What else should I try?

Answer

Brock Adams picture Brock Adams · Oct 25, 2012

Update:

As of version 1.10 (June 20, 2013), Greasemonkey now supports the GM_setClipboard() function.
Use like so:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_setClipboard
// ==/UserScript==

GM_setClipboard ("The clipboard now contains this sentence.");


Older GM versions:

This is very difficult to do with Greasemonkey since GM devs refuse to support it and FF and Flash security settings must be overcome.
You can do it if the copy will be initiated by a manual click. In which case, use one of the techniques from this question.

If you wish to have some kind of fully-automatic clipboard operation, then you will have to develop your own add-on or plugin for your GM script to use.


Scriptish has supported this for years:

If you are open to switching scripting add-ons, note that Scriptish provides GM_setClipboard() to set the clipboard. (But no function to read it?!)

Scriptish is not perfect, but it is better than Greasemonkey in a few ways. (Note I'm not affiliated with either add-on, nor am I completely happy with either.)

Most GM scripts will run in Scriptish with no problem.


As for the code snippets, from the question; they are essentially the same thing (the first just accounts for the GM sandbox). That approach has been obsolete for many versions of Firefox and the replacement code is poorly documented.
You'll have to use techniques that require user interaction, or you'll have to write a custom helper add-on.