Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: How to get current webpage url from background.html

From my knowledge it is not possible directly by getting tab.url (only possible in the popup.html) and doing message passing also requires that popup.html be open. Is there anyway to bypass this and get the current page url from background.html?

My best shot was with message passing, which I used this code in background.html

var bg = chrome.extension.getPopupPage(); 
var myURL = bg.myURL; 

then in popup.html I had:

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

Anyways the above does't work at all. Anybody know of a way to do this without having to actually open up the popup?

like image 916
Calvin Avatar asked Jun 23 '11 09:06

Calvin


1 Answers

chrome.tabs.query is supported from background pages, of course as long as you have the tabs permission. This is the supported route as of Chrome 19.

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

Note that currentWindow is needed because it would otherwise return the active tab for every window. This should be guaranteed to only return one tab.

Of course, keep in mind that this is an asynchronous API – you can’t access any data it provides except from within the callback function. You can store values (such as url here) at a higher scope so another function can access it, but that will still only provide the correct result after the callback is executed.


(The below is my original answer kept for posterity – this method is no longer necessary, requires an always-running background page, and getSelected() is deprecated.)

First put this in background.html and make the myURL variable global:

var myURL = "about:blank"; // A default url just in case below code doesn't work
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked 
    chrome.tabs.getSelected(null, function(tab) {
        myURL = tab.url;
    });
});

Then run this in popup.html when you want to get the page url:

chrome.extension.getBackgroundPage().myURL;

So if I were to make that appear inside the popup and I went to Google and clicked your page or browser action, I'll see http://google.com/webhp in the popup.

like image 134
kirb Avatar answered Sep 24 '22 22:09

kirb