Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greasemonkey\JavaScript Copy to Clipboard button

I am trying to write a JavaScript script to add to greasemonkey that adds a button after an element. The onClick for this button should copy the parents element text to the keyboard. I have seen plenty of examples that copy already selected text to the clipboard such as this:

    <SCRIPT LANGUAGE="JavaScript">
    <!-- Begin
    function copyit(theField) {
    var selectedText = document.selection;
    if (selectedText.type == 'Text') {
    var newRange = selectedText.createRange();
    theField.focus();
    theField.value = newRange.text;
    } else {
    alert('Alert: Select The text in the textarea then click on this button');
    }
    }
    // End -->
    </script>
    <input onclick="copyit(this.form.text_select)" type="button" value="Click Here to Copy the Highlighted Text" name="copy_button">

Found here.

I have also found that you can select text in input elements. I have tried combining both techniques, as well as many others with no viable solution yet. I am not even sure why the code above copies to the clipboard. Does anyone have a solution to this?

like image 961
javamonkey79 Avatar asked Nov 25 '08 06:11

javamonkey79


2 Answers

If you took the time to read the full article, the author states this doesn't work for Firefox...
Actually, I think it doesn't even work for IE, as it does nothing related to the clipboard!

There is a technique using Flash, because by default, Firefox inhibits clipboard access for security reasons.
Otherwise, the classical way to do copy is:

var tc = textToCopy.replace(/\n\n/g, '\n');
if (window.clipboardData) // IE
{
  window.clipboardData.setData("Text", tc);
}
else
{
  unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  const clipboardHelper = Components.classes
      ["@mozilla.org/widget/clipboardhelper;1"].
      getService(Components.interfaces.nsIClipboardHelper);
  clipboardHelper.copyString(tc);
}

after enabling copy (for a given site).

like image 147
PhiLho Avatar answered Sep 25 '22 03:09

PhiLho


Are you sure your example works? It does not in my browser. But take a look at the following page: http://www.jeffothy.com/weblog/clipboard-copy/

like image 24
wimh Avatar answered Sep 23 '22 03:09

wimh