8

I'm using a chrome extension with a button in the popup.html that opens a new tab. The destination URL of the new tab holds the URL of the current (original) tab as a parameter.

For instance: when fired from http://stackoverflow.com/, the new tab should have an URL like http://www.mydestination.com/index.php?url=http://stackoverflow.com/

Here's my js:

document.addEventListener('DOMContentLoaded', function (tab) { 

    document.getElementById('button').addEventListener("click", function(tab) {
        chrome.tabs.create({url: 'http://www.mydestination.com/index.php?url=' + tab.url});
    }); 

})

The new tab is opened perfectly, but the URL is http://www.mydestination.com/index.php?url=undefined (url = undefined).

I reckon the manifest.json holds the right permissions:

{      
"manifest_version": 2,
"name": "My project",
"version" : "1.7",
"browser_action": {
  "default_icon" : "img/icon.png",
  "default_title" : "My project",
  "default_popup": "html/main.html" 
},
"permissions": [
  "tabs"
],
"icons": {
  "16": "img/icon.png"
}
}

Any clues on how to get the url transported properly?

Rob W
  • 341,306
  • 83
  • 791
  • 678
Lionel
  • 83
  • 1
  • 3
  • whoa wait, "tab" would actually be the click event, dont you mean `addEventListener("click", function(evt, tab) {...` ? – 1337holiday May 13 '13 at 02:20

2 Answers2

5

The problem is that current tab is your chrome popup. In this case you don't have valid URL. You have to select your tab. To do this you can use chrome.tabs.query. Select current window with active tab:

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('button').addEventListener("click", function () {
        chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        }, function (tabs) {
            chrome.tabs.create({
                url: 'http://www.mydestination.com/index.php?url=' + tabs[0].url
            });
        });
    });
});
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
2

The problem is that you are passing tab as a parameter when it has nothing to do with the events. While some chrome.* apis do include a tab object as a parameter, you can't just add it on like that and expect it to have the info you want. You could do something like this:

document.addEventListener('DOMContentLoaded', function () { 
  document.getElementById('button').addEventListener("click", function() {
    chrome.tabs.query({active:true, currentWindow:true},function(tab){
      // Just doing it like this to make it fit on the page
      var newUrl = "http://www.mydestination.com/index.php?url=" + tab[0].url;
      chrome.tabs.create({url:newUrl});
    });
  }); 
});
BeardFist
  • 8,031
  • 3
  • 35
  • 40