Chrome Extensions - Copy Link Google Search

145 views Asked by At

I am creating a Chrome Extension which places a button next to the link on a Google Search and when pressed it will copy the link to the clipboard. However I am not able to get it working.

Here is the Manifest File.

{
 "content_scripts":[
{
  "all_frames":false,
  "js":[ "js/jquery.min.js", "js/jquery-ui.min.js" "js/script.js" ],
  "matches":[ "https://www.google.com.au/*" ],
  "run_at":"document_end"
}
],
"description":"Copies link to the clipboard.",
"icons":{
"16":"img/icon-16.png",
"32":"img/icon-32.png",
"64":"img/icon-64.png",
"128":"img/icon-128.png",
"256":"img/icon-256.png",
"512":"img/icon-512.png"
},
"manifest_version":2,
"minimum_chrome_version":"40",
"name":"Copy Link",
"version":"0.1",
"version_name":"0.1 beta"
}

Here is the Script File.

  function copy() {
   var h = $("a[href]");
   h.document.execCommand('copy');
   $("button").after(h);
  }
  $(document).on("DOMSubtreeModified", copy);

Here is an inspected element from a search result.

  <h3 class="r">
   <a href="http://www.speedtest.net/">Speedtest.net by Ookla - The Global   Broadband Speed Test</a>
  </h3>
1

There are 1 answers

2
Dayton Wang On

It's because document.execCommand is not allowed in content script. Only background.html and popup.html are allowed clipboard access. If you want to copy anything in the content script, you have to send the data to background with MessagePassing of chrome.