views:

1201

answers:

3

I'm having fun Google Chrome extension and I just want to know how I can store the URL of the curent tab in a variable.

Maybe it's in the doc, but doesn't want to load :s

+5  A: 

A friend answers to my question.

First, you've to set the permissions for the tab API :

"permissions": [
    "tabs"
]

And to store the URL :

chrome.tabs.getSelected(null,function(tab) {
    var tablink = tab.url;
});
Axiol
The second part of code is for the case of a popup file
Axiol
The reason why its just for the popup (page action, browser action) is because your sending in a "null" into the first parameter.http://code.google.com/chrome/extensions/tabs.html#method-getSelectedThe docs state the first parameter is the windowId, if you want to use that in options, or background page, you would need to put in the window id or you will get the current tab your viewing which is undefined, options respectively.
Mohamed Mansour
A: 

Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)

Additionally it is a nice working code example, which i prefer motstly over reading Documents.

Can be found here: Email this page

bastianneu
+1  A: 

The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:

var tablink;
chrome.tabs.getSelected(null,function(tab) {
    tablink = tab.url;
});
console.log(tablink);

The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.

Try something like:

chrome.tabs.getSelected(null, function(tab) {
    myFunction(tab.url);
});

function myFunction(tablink) {
  // do stuff here
  console.log(tablink);
}
Nyk Cowham

related questions