1

Would like to access the current tab url in background.js

Had already used following code in background.js

 window.chrome.tabs.query({ "active": true, "windowId": window.chrome.windows.WINDOW_ID_CURRENT },
    (tabs) => {
        console.log("Tab Url ", tabs);
        if (Array.isArray(tabs) && tabs.length > 0 && tabs[0]["url"]) {
            console.log("Tab Url ", tabs[0]["url"]);
        }
    }
);

chrome.tabs.getAllInWindow(undefined, function (tabs) {
    for (var i = 0, tab; tab = tabs[i]; i++) {
        console.log(tab);
        if (tab.url) {
            console.log(tab.url)
        }
    }
});


chrome.tabs.getCurrent(function (tab) {
    console.log(tab.url);
});

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

With and without parent function

window.chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab){...code})

manifest.json

"background": {
  "scripts": [
    "background.js"
  ],
 "persistent": true
},
"permissions": [
  "identity",
  "activeTab",
  "tabs"
],

For all the above results, I am receiving undefined for the current URL.

Any guidance is appreciated.

Ajay
  • 4,773
  • 3
  • 23
  • 36
  • Assuming you did reload your extension after adding the required `tabs` permission, there are two problems: a) [chrome bug](/a/63886442) when devtools is open for the background script and b) your current background script isn't really usable, you need an API event, [more info](/a/63966400) – wOxxOm Sep 21 '20 at 12:30

1 Answers1

0

Rather than doing window.chrome.tab.query you can just do chrome.tabs.query. Also in the updated version of the chrome API, you can get the current tab url by passing currentWindow and active as true.

So, the request to get the current tab becomes :

const currentTab = chrome.tabs.query({currentWindow: true, active: true}, function(){});
console.log(currentTab.url);