How to use JS to copy chrome app content to clipboard?

207 views
Skip to first unread message

Liu Liu

unread,
May 24, 2015, 6:43:33 PM5/24/15
to chromi...@chromium.org
Hi,

What I'm trying to accomplish:
- click on a button, copy content XYZ to clipboard. I'm using window.getSelection().addRange() , and document.execCommand('copy').

My issue:
I have some working code in js fiddle: http://jsfiddle.net/liuliuweb/3dfzx8og/
But when I package it as a chrome app, it doesn't work: https://github.com/auxdesigner/issue-test

I did some console testing, and my assumption is that the "window.getSelection().addRange()" part didn't work in Chrome packaged app.

Any thoughts? I'd love to know if there is a better way to do this.
Thanks in advance!


Jarek Foksa

unread,
May 26, 2015, 4:54:30 AM5/26/15
to chromi...@chromium.org
Maybe you are missing the "clipboardRead" and "clipboardWrite" permissions in your manifest.json file? Also, it's possible to put data into the clipboard without having to rely on Selection and Range APIs:

  var setClipboardData = function(data) {
   
var copyListener = function(event) {
      document
.removeEventListener("copy", copyListener);
     
event.preventDefault();
     
event.clipboardData.items.add(data, "text/plain");
   
};

    document
.addEventListener("copy", copyListener);
    document
.execCommand("copy");
 
};

 
var emailLink = document.querySelector('.js-emaillink');  
  setClipboardData
(emailLink.textContent);
Reply all
Reply to author
Forward
0 new messages