1

I am building out my first Google Chrome Extension and want to create something that can read and write to the system clipboard. I am currently putting all the js in a script imported by the popup.html for the extension.

I also have permissions declared in the manifest.json for clipboard-read and clipboard-write.

I was able to write data into the clipboard, but I am unable to read from it.

I have a button on the popup.html that has an id and in the js I am getting element by id and adding a eventlistener for click that fires a function called paste which in turn invokes navigator.clipboard.readText(). From my understanding, that is supposed to prompt for permission, but it is not doing anything.

Do you know if it's okay to invoke readText from the popup.html? If so, how would get the prompt to show up? Thanks in advance!

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
srac1777
  • 11
  • 2
  • Most likely a bug in Chrome as I remember seeing it on https://crbug.com. You'll have to use the classic approach - look up "document.execCommand paste". Note, the permission names are clipboardRead and clipboardWrite. – wOxxOm Jan 23 '19 at 11:04
  • @wOxxOm thank you for the suggestion, will test out the document.execCommand. I noticed some docs say the permission for clipboard read is clipboard-read and others say clipboardRead. Strange. – srac1777 Jan 23 '19 at 21:06
  • Extension permissions were always camelCase. Anything else is a mistake. – wOxxOm Jan 24 '19 at 04:34
  • Used the document.execCommand and it worked! Thanks @wOxxOm – srac1777 Jan 26 '19 at 02:27
  • duplicate: https://stackoverflow.com/questions/22702446/how-to-get-clipboard-data-in-chrome-extension/43375402 – fxnoob Jun 05 '19 at 14:36

1 Answers1

-2

If you include JQuery as a background script you can use this (I use this all the time in my chrome extensions) to move text to the clipboard and then if you have a past method you can do that in the settimeout...

function copyUsingJquery(element_id) {
            $(element_id).attr("contenteditable", true)
              .select()
              .on("focus", function () {
                  document.execCommand('selectAll', false, null)
              })
              .focus();
            document.execCommand("Copy");
            $(element_id).removeAttr("contenteditable");

            setTimeout(function () {
                //deslect text on page after a few seconds
                //$(element_id).trigger("blur");
                window.getSelection().removeAllRanges();
            }, 5000);

        }

and then call the above function with the following where some_html is your element (could be a div/must be visible or positioned to not be visible...

copyUsingJquery("#some_html");

Hope this helps.

Rob
  • 1,226
  • 3
  • 23
  • 41