2

i'm making a chrome extension that opens a web-site if the current tab is not the same web-site, so i managed to get all of the tabs like this:

chrome.tabs.getAllInWindow(null, allTabs);

and i wrote a function to display it:

   function allTabs(tabs) {
        var tabsURLS = '';
        for (var i = 0; i < tabs.length; i++) {
            tabsURLS = tabs[i].url + '\n';
        }
        alert(tabsURLS);
    }

but i need to get the current page url so i get the current tab by this:

var object=chrome.tabs.getCurrent(function(){;});

but i cant get to page properties like id or url and this alert shows "undefined" ...

alert(object);

while this alert doesn't work at all

alert(object.id);

in the end, i read this page chrome.tabs and i was shocked when i read this line

getCurrent
chrome.tabs.getCurrent(function callback)
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).

so i don't think that there is a solution of getting the current opened tab from chrome extension...

Tarek
  • 1,904
  • 2
  • 18
  • 36
  • possible duplicate of [How to get the currently opened tab's URL in my page action popup?](http://stackoverflow.com/questions/10413911/how-to-get-the-currently-opened-tabs-url-in-my-page-action-popup) – Rob W Jul 20 '13 at 10:50

4 Answers4

5

I believe that you need to use getSelected instead

<html>
<head>
<script>

    chrome.tabs.getSelected(null, function(tab) {
        var tabId = tab.id;
        var tabUrl = tab.url;

        alert(tabUrl);
    });

</script>
</head>
G-Man
  • 7,232
  • 18
  • 72
  • 100
  • now there is another problem, the url won't update from the first time , the page opens twice and when the url changes i must click twice on the extension to open a new tab.... is there a solution for that ? – Tarek Jul 20 '13 at 11:11
1

the final code was like this, and it worked just fine.. :

var tabUrl;
chrome.browserAction.onClicked.addListener(function(activeTab) {
    var x=activeTab.url;
    var newURL = "https://www.google.com";
    if (x!= newURL) {
        //to open a page in a new tab
        chrome.tabs.create({url: newURL,"selected":true});
        //to open the page with the current tab
        chrome.tabs.update(activeTab.id, {url:newURL});
    }

});
Tarek
  • 1,904
  • 2
  • 18
  • 36
0

The current accepted answer is out of date.

According to MDN, tabs.getSelected() is depricated

Use this instead:

tabs.query({active: true})

James Douglas
  • 3,328
  • 2
  • 22
  • 43
-1

Ensure to set the correct permissions in manifest.json to access tab information:

"permissions": [
    "tabs",
    "http://*/*"
],

After that, you can determine the URL by using

chrome.tabs.getSelected(null, function (tab) {
    alert(tab.url);
});
Matthias Kleine
  • 1,228
  • 17
  • 15