0

I'm making a chrome extension where the user can press a button and text will get copied to their clipboard. I've written the HTML and Javascript to do this and the code works when I open the HTML file in my browser. The issue is that when I open the extension (running that same HTML file), the button won't copy any text to the clipboard. I do have the permission "clipboardWrite" enabled in my manifest.json file and chrome://extensions also says "Modify data you copy and paste" when I go to details > permissions.

To try to fix the issue, I've reloaded the extension, deleted and re-added the unpacked folder, and restarted my computer; none of which solved my problem. I've also tested it in multiple browsers and it fails to work in all of them.

Here's some code that re-creates the issue I'm getting:

popup.html:

<!DOCTYPE html><html>
    <body>
        <script>
            /*Function that copies text. This works fine in a browser but not in the extension*/
            function clip(string) {
            const ta = document.createElement('textarea'); //creates a constant of a textarea
            ta.value = string; //adds 'string' parameter into the textarea
            ta.setAttribute("id", "temptextarea");
            document.body.appendChild(ta); //adds an instance of the textarea
            ta.select(); //selects the text in the textarea (may be the issue for chrome extension)
            document.execCommand('Copy'); //copies the selected text
            document.body.removeChild(ta); //removes the instance of the textarea
            }
        </script>
        <!--Button that copies text.-->
        <button onclick="clip('This text gets copied')">Copy Text!</button>
    </body>
</html>

manifest.json:

{
    "manifest_version": 2,
    "name": "My Extenstion Name",
    "version": "1.0.0",
    "permissions": [
      "clipboardWrite"
    ],
    "browser_action": {
        "default_popup": "popup.html",
        "default_title": "My Extension Name"
    }
  }

When running this code snippet in a browser tab, you'll get the expected result: it will copy "This text gets copied" to your clipboard when you click the button. For whatever reason, when you put those two files into a folder and upload it to chrome://extenstions, the text doesn't get copied to your clipboard. This confuses me because logically, the only reason it wouldn't be able to work in the extension is because of insufficient permissions, but as I stated earlier, it does have permission to write to the clipboard.

Thanks in advance!

Gav Hern
  • 21
  • 6

1 Answers1

0

The reason this code isn't working is because chrome extensions throw an exception if you use onclick="". You need to use an event listener in this case.

Gav Hern
  • 21
  • 6