Find URL of current tab. Making a FireFox Browser add-on

WillJones picture WillJones · Jul 20, 2012 · Viewed 7.3k times · Source

I'm making a Firefox Browser Add-on and need to find the url of the current tab

I've tried this post Opening a URL in current tab/window from a Firefox Extension but it tells me that 'window' is not defined. (I think because I am making an add-on rather than an extension.)

Here's what I've tried to do:

var widgets = require('widget');
var tabs = require('tabs');

var widget1 = widgets.Widget({
  id: "widget1",
  label: "widget1",
  contentURL: "http://www.mozilla.org/favicon",
  onClick: function() {
    console.log(tabs.url);
  }
})

I've made a widget such that when I click it the url of the current tab should be 'console.log'ed.

Doesn't seem to happen! Keep getting "info: undefined" which clearly means that tabs.url isn't returning anything. But this seems to be the way to use it according to https://addons.mozilla.org/en-US/developers/docs/sdk/1.5/packages/addon-kit/docs/tabs.html

Anyone have any ideas?

Thanks,

Will

Answer

therealjeffg picture therealjeffg · Jul 29, 2012

You're almost there:

const { ActionButton } = require("sdk/ui/button/action");
const clipboard = require("sdk/clipboard");
const tabs = require('sdk/tabs');

let button = ActionButton({
  id: "my-button-id",
  label: "Button Label",
  icon: {
    "32": "chrome://mozapps/skin/extensions/extensionGeneric.png"
  },
  onClick: function(state) {
    let url = tabs.activeTab.url;
    console.log("active tab url:", url);
    require("sdk/notifications").notify({
      title: "Active Tab's Url is "+url,
      text: "Click to copy.",
      onClick: function() {
        clipboard.set(url);
      }
    });
  }
});

You should check out the documentation on the tabs module.

Note: I've updated this code example to use the new ui modules available since Firefox 29 - the 'widget' module used in the original question was valid at the time but has since been deprecated and then removed.