To clarify, we are talking about the relationship between the pop-up page from the Action browser and the background of the script?
In any case, you have quite a few errors in the code.
The first completely ignores the fact that all callbacks in the chrome api are asynchronous .
In the background page
var tabURL = "Not set yet"; chrome.tabs.getCurrent(function(tab){ tabURL = tab.url; });
Same thing in popup.js
chrome.runtime.sendMessage({greeting: "GetURL"}, function(response) { tabURL = response.navURL });
The second error is that chrome.tabs.getCurrent does not give you the current tab selected by the user in the main window. docs says:
Gets the tab with which this script call is executed. It can be undefined if called from a context without tabs (for example: background page or popup).
This way you will get undefined for all your requests because you are calling it on the background image. What you need to do is use the chrome.tabs.query method to get the active tabs.
So, after fixing all the problems, the new code should look something like this:
background.js
chrome.runtime.onMessage.addListener( function(request,sender,sendResponse) { if( request.greeting === "GetURL" ) { var tabURL = "Not set yet"; chrome.tabs.query({active:true},function(tabs){ if(tabs.length === 0) { sendResponse({}); return; } tabURL = tabs[0].url; sendResponse( {navURL:tabURL} ); }); } }
popup.js
function getURL() { chrome.runtime.sendMessage({greeting: "GetURL"}, function (response) { tabURL = response.navURL; $("#tabURL").text(tabURL); }); }
jusio source share