Mark Allison
Mark Allison

Reputation: 7228

How to copy to clipboard in chrome extension with a link?

I have recently created a chrome extension for the first time. I have a copy button on my page which works fine when the extension is loaded as a web page. However, when I load it as an extension the copy function doesn't work.

My manifest.json permissions looks like this:

"permissions": [
  "webNavigation",
  "storage",
  "clipboardWrite",
  "clipboardRead"
]

The code in my popout.html page to copy looks like this:

        <div id="legacyCopyLabel">
            <a onclick="copyText(getElementById('legacy'))" class="alignright">COPY</a>
        </div>

and the copyText() function in my javascript code looks like this:

function copyText(element) {
    var range, selection, worked;

    if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(element);
      range.select();
    } else if (window.getSelection) {
      selection = window.getSelection();        
      range = document.createRange();
      range.selectNodeContents(element);
      selection.removeAllRanges();
      selection.addRange(range);
    }

    try {
      document.execCommand('copy');
      updateStatus ('Copied address', 'info');
    }
    catch (err) {
      alert('Unable to copy the address');
    }
  }

Full code is here if you want to look: https://github.com/markallisongit/handcash-chrome

Chrome extension is on the chrome store here: https://chrome.google.com/webstore/detail/handcash-handle-converter/bnkohbkbipagdhplhkhgonbalbjigpoh

Upvotes: 2

Views: 2076

Answers (1)

Denis L
Denis L

Reputation: 3292

It doesn't work because you use inline JS: <a onclick="...">.
According to Chrome's Content Security Police:

Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers (e.g. ).

The solution will be to put your code into a separate .js file and include it as a usual JS-script.

Upvotes: 3

Related Questions