3
votes

I have a browserAction extension testing on chrome 31.0.1650.57. I want to get active tab url when the user click on the extension icon, save it and use it later.

I am able to do that when using tabs permission. But this permission has a lot of power (that I don't need) and users are complaining about this.

I followed the article to switch to activeTab permission http://developer.chrome.com/extensions/activeTab but it only works when there is no popup. As you can see in the make_page_red example.

chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  console.log("★ tab.url", tab.url);
});

You can check by changing the make_page_red example manifest file to add a default popup like this:

{
  "name": "Page Redder",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "Make this page red",
    "default_popup": "popup.html"  ←-------------------

  },
  "manifest_version": 2
}

Now because I have a default popup the browserAction.onClicked listener is not called anymore.

How can I get current tab url and still have my popup opening?

Thanks

1
Could you show what you have already (manifest and popup.html)? I've gotten activeTab to work with a browser action at stackoverflow.com/a/22057017/2336725Teepeemm
@Teepeemm I tried with your answer but the tab object has no url propertyredochka
I believe that popup.html means that browserAction.onClicked is not called. Perhaps have popup.hmlt just get the tab url directly? And could you post more of what you have already?Teepeemm
@Teepeemm I am using the make_page_red sample. See my updated description. Thanksredochka

1 Answers

7
votes

browserAction.onClicked is not called anymore (as you noted), so just skip that:

popup.js:

chrome.tabs.query({active:true,currentWindow:true},function(tabArray){
    console.log(tabArray[0].url);
});

And of course, have popup.html load popup.js with a script tag. (And I'm not sure what you're background script is doing.)

Edit:

In addition to the above, my extension has two other files. manifest.json is copied from yours, but has the background section deleted. The only other file is popup.html (from memory, so bear with me):

<html><body><script type="text/javascript" src="popup.js"></script></body></html>

To view the console, I click the browser action, which brings up a 50 pixel square window. Right click on that, "inspect element", and click console to view the url.