Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  132] [ 1]  / answers: 1 / hits: 29153  / 13 Years ago, thu, june 23, 2011, 12:00:00

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?


More From » url

 Answers
127

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.


[#91553] Tuesday, June 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacyl

Total Points: 131
Total Questions: 105
Total Answers: 94

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;