Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy to clipboard - not working in FF,Chrome

I am using below mentioned javascript to copy the text to clipboard. Its working in IE, but not working in Firefox and Chrome.

Please advice me,What is wrong?

   function setDataToclipboard() 
{

var str=document.getElementById("populatedString").value; 

if (window.clipboardData && clipboardData.setData) {
    clipboardData.setData("Text", str);
    alert("Copied!");
}
}
like image 416
Naju Avatar asked Jan 22 '13 13:01

Naju


3 Answers

See the documentation for clipboardData, specifically the section that reads:

There are no standards that apply here.

You are using proprietary Microsoft gubbins, so it shouldn't be expected to work on other browsers.

See this question for cross-browser techniques to access the clipboard.

There is a draft of a standard for accessing the clipboard but I'm not aware of any implementations of it in the wild (and canIuse doesn't know of any either).

like image 179
Quentin Avatar answered Sep 27 '22 15:09

Quentin


I had this same problem with Chrome and other browsers recently. However, recently, I found this code works in a contenteditable field in certain browsers:

clipboard = e.originalEvent.clipboardData;
clipboard.setData('text/plain', plainData);
clipboard.setData('text/html', htmlData);

NOTE: e in this case is the copy and/or cut event. This event fires and is retrievable in an onCopy() or onCut() action.

This code is confirmed to work in the latest versions of the following browsers:

  • Chrome (PCs/Macs and Android)
  • Android 4.4+ WebView (as long as you update from the Play Store) -> good news for Android Devs
  • Firefox
  • Safari (Mac only)

Internet Explorer seems to work with window.clipboardData.setData instead, but keep in mind that the IE clipboard will only accept 'text' and 'url' data.

While the following browsers can access the system clipboard object, these are unable to set data into the clipboard using clipboard.setData:

  • MS Edge
    • gives an UntrustedDragDrop object into the clipboard instead...
    • also, setData returns true... when it doesn't work. setData returns undefined in all other browsers
  • Android WebView -> below 4.4
  • iOS Safari and WebView - yay iOS!
like image 38
Jeremy Jao Avatar answered Sep 27 '22 15:09

Jeremy Jao


I think the window.clipboardData is IE only. Accessing the clipboard is a security concern, and thus cannot be done easily in FF or Chrome.

Please see this thread: How do I copy to the clipboard in JavaScript?

like image 40
David Avatar answered Sep 27 '22 16:09

David