views:

3640

answers:

2

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?

+1  A: 

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/

Wimmel
It works in FF 3.0.4, but you have to select the text in order to get the copy button to work. I have seen that blog post, and it relies on using flash to copy, which will not work for what I am trying to do. Thank though. :)
javamonkey79
+3  A: 

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).

PhiLho
I did take the time to read the whole article -- I just missed the "note"; there is no reason to be testy, we all make mistakes. Nonetheless, your solution is the correct way, thanks.
javamonkey79