0

I am trying to read a value from the clipboard into a Chrome extension popup. When the following code executes it never gets passed the console.log statement 'popup.js::ReadFromClipboard: inside try block'. The document.hasfocus() call returns 'true'. The extension does not throw any errors.

Any advice would be gratefully received.

popup.js:

document.getElementById("ReadFromClipboard").addEventListener("click", async (ev) => {
  console.log("popup.js::ReadFromClipboard: does document have focus (1)? " + document.hasFocus());
  ev.preventDefault(); // this has no effect
  try {
        console.log("popup.js::ReadFromClipboard: inside try block");
        var clipCopy = await navigator.clipboard.readText(); //THIS NEVER APPEARS TO EXECUTE
        console.log("popup.js::ReadFromClipboard: readText clipCopy= " + clipCopy);
      } catch (err) {
          console.log("popup.js::ReadFromClipboard: readText error = " + err);
      }
}, false);

popup.html:

<html meta-charset-utf-8  >
  <head>
    <meta charset="utf-8">
    <title>KeyOnce</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div id="Message" width="80"></div>
    <button type="button" id="ReadFromClipboard"> Read from Clipboard</button><br>
    <script src="popup.js"></script>
  </body>
</html>

manifest.json: `{ "name": "Clipboard Problem", "description": "Test Read Clipboard", "version": "1.0",

"permissions": [
  "activeTab",
  "tabs",
  "clipboardRead"
],
   
"action": {
  "default_icon": "icon.png",
  "default_title": "Test Read Clipboard",
  "default_popup": "popup.html"
},

"manifest_version": 3

} `

Ive tried to access the Clipboard in a contents script but this complains that the document does not have focus - it has passed to the popup.html when it was clicked.

Ive tried the long-hand form of Promise clipPromise = navigator.clipboard.readText().then (..).catch() and the readText() method simply does not appear to execute.

I have tried introducing event.preventDefault() call into the async call handler for the click but this has no effect.

  • There's no server in an extension so submitting simply resets the page. Use a normal `button` element instead. – wOxxOm Mar 17 '23 at 22:15
  • As per wOxxOm's suggestion I changed to use – Howard Ricketts Mar 19 '23 at 13:57
  • Probably a bug in Chrome. Use the old [execCommand method](https://stackoverflow.com/questions/22702446/how-to-get-clipboard-data-in-chrome-extension). – wOxxOm Mar 19 '23 at 15:07
  • All of the documentation points to execCommand having been deprecated and to use the new Clipboard API. – Howard Ricketts Mar 19 '23 at 21:06
  • This is not a duplicate of 'Popup refreshing on form submit in chrome extension'. – Howard Ricketts Mar 19 '23 at 21:07
  • The fact that it's deprecated doesn't mean that it can't be used. There's no workable replacement anyway. – wOxxOm Mar 19 '23 at 21:14

0 Answers0