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?
chrome.tabs.queryis supported from background pages, of course as long as you have thetabspermission. This is the supported route as of Chrome 19.Note that
currentWindowis 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
urlhere) 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:
Then run this in popup.html when you want to get the page url:
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/webhpin the popup.