0

I'm trying to make my first WebExtension (a button on toolbar) to copy the current URL to clipboard. What should I add to background.js?

I have this manifest.json file:

{
    "manifest_version": 2,
    "name": "Copy URL to Clipboard",
    "description": "desc",
    "version": "1.0",
    "homepage_url": "",

    "icons": {
        "48": "icons/clipboard-48.png"
    },

    "background": {
      "scripts": ["background.js"]
    },

    "browser_action": {
      "default_icon": {
        "16": "icons/clipboard-16.png",
        "32": "icons/clipboard-32.png"
      }
    }
}

I tried something like this but it doesn't work:

function copyURL() {
  var url = document.location.href;
  url.select();
  document.execCommand("Copy");
}

browser.browserAction.onClicked.addListener(copyURL);
Makyen
  • 31,849
  • 12
  • 86
  • 121
FloatingAway
  • 13
  • 1
  • 6
  • Are you specifically wanting to do this from within a `browserAction.onClicked` handler? – Makyen Oct 29 '17 at 03:28
  • Your question is actually a combination of three different questions: Related/duplicates: [Copy text to clipboard from background script in a Firefox WebExtension](https://stackoverflow.com/q/45622608), [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/q/400212), and [chrome.tabs.executeScript(): How to get result of content script?](https://stackoverflow.com/q/41577988) (just for how to use `tabs.executeScript()` to inject code from a `browserAction.onClicked` listener). – Makyen Oct 29 '17 at 03:40
  • "Are you specifically wanting to do this from within a browserAction.onClicked handler?" Not necessarily with browserAction.onClicked but using whatever method that works. – FloatingAway Oct 29 '17 at 03:51
  • Another time, it's helpful to break your overall task into smaller sub-tasks and ask questions about those, rather than ask about a larger set of functionality. This question is really: A) How do I copy to the clipboard (answered in a duplicate); B) How can I copy to the clipboard from the background script in a WebExtension (you can't, previously answered). Because of the answer to (B) we *don't ask* C) How do I get the active tab's URL in the background script (various duplicates), but we do ask D) How do I execute a content script in the active tab from a `browserAction.onClicked` listener. – Makyen Oct 29 '17 at 03:53
  • Because you tried to get the active tab's URL from a background script using `document.location.href` (which is not the way to do it, and implies that you're not familiar with the architecture of WebExtension based extensions), I suggest you read the [Anatomy of a WebExtension](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension) page (perhaps work through reading the pages linked from there). It has overall architecture information which should help your understanding of how things are generally organized/done. – Makyen Oct 29 '17 at 03:56

0 Answers0