Why doesn't chrome.tabs.query() return the tab's URL when called using RequireJS in a Chrome extension? Why doesn't chrome.tabs.query() return the tab's URL when called using RequireJS in a Chrome extension? google-chrome google-chrome

Why doesn't chrome.tabs.query() return the tab's URL when called using RequireJS in a Chrome extension?


You don't see a URL because you've only set the activeTab permission (not the tabs) permission AND the last focused window is the developer tools (for which you don't have activeTab access) (and since Chrome 41, devtools tabs/windows are invisible to extensions, so tabs will be an empty array).

The good news is that this problem is specific to the devtools window being opened for your extension page, so the issue only occurs during development and not during actual use by users.

Extension popups are associated with a window, so you can use chrome.tabs.query with currentWindow:true to get the correct answer:

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


To overcome the devTools bug that Rob W. reported in his post, the following getActiveTab workaround seems to consistently work for me (even when there are multiple devTools windows open). It works by always saving a reference to the activeTabId in the background page, whenever the tabs.onActivated event fires.

var activeTabId;chrome.tabs.onActivated.addListener(function(activeInfo) {  activeTabId = activeInfo.tabId;});function getActiveTab(callback) {  chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {    var tab = tabs[0];    if (tab) {      callback(tab);    } else {      chrome.tabs.get(activeTabId, function (tab) {        if (tab) {          callback(tab);        } else {          console.log('No active tab identified.');        }      });    }  });}