Ricardo
Ricardo

Reputation: 1672

Copy and paste the selected text to the clipboard using JavaScript

I'm building a custom right-click menu for my system and I need to know how can I make a JavaScript function to copy the selected text, basically 100% like the original right-click menu does.

I'm aware of the Flash work-arounds. I want to do this in JavaScript.

Every answer I've seen so far is only a half-answer because none of them explains how to make a copy button for the selected text - all what they do is copy a pre-defined text or a text from a textbox.

Upvotes: 0

Views: 2904

Answers (4)

Maxx
Maxx

Reputation: 4072

For non-IE browsers you will most likely have to use a flash solution. For IE, however, this method works perfectly:

function copyToClipboard(s) {           //only works in IE :(
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('text', s);
    }
}

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Modern Day Browsers block access to the clipboard. The user has to have the security setting correct.

There are flash work-arounds, but they are not the best.

Upvotes: 1

Joe
Joe

Reputation: 82554

A workable cross-browser approach (minus iOS) would be to use ExternalInterface and setClipboard. So you would have a swf, flash file, that only listens to a function you call from Javascript to set the clipBoard.

Upvotes: 0

wolv2012
wolv2012

Reputation: 429

no idea if this will work, but a google search yielded:

function getSel(){
  var w=window,d=document,gS='getSelection';
  return (''+(w[gS]?w[gS]():d[gS]?d[gS]):d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}

http://snippets.dzone.com/posts/show/2914

Upvotes: 0

Related Questions