1

//this is in the popup

function getURL(){
    var url;
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        //gets a list containing the active page and assigns it to tabs where the first place is the        active tab
        chrome.tabs.sendMessage(tabs[0].id, {type: "getURL"}, function(answer) {
          //sends a messge to the viewed in order to get its url
            url = answer;
            
          });
    });
    return url;
}
//this is in the content script of the extension
chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {
    if(message.type == "getURL")
    {
      console.log(window.location);
      sendResponse(window.location.origin);
    }
  }
);

so the problem im encountering is when i run the getURL func it returns undefined and i assume its beacuse it reaches the return before getting the answer how would i make this function always return the url is there some way to make it "wait" for the answer?

  • I would hope you’re not going to use this in an extension to spy on peoples URLs? – evolutionxbox Feb 22 '20 at 20:46
  • no im making an adblock and its for the purpose of whitelisting urls – Barak Gzlee Feb 22 '20 at 20:50
  • Good good. Do you know if `chrome.tabs.query` is asynchronous? – evolutionxbox Feb 22 '20 at 21:32
  • 1
    All `chrome` API callbacks are asynchronous so you need to use the value inside the callback or promisify the API as explained in the linked answers, see also [WebExtension polyfill](https://github.com/mozilla/webextension-polyfill/) for a modern solution. P.S. no need for sendMessage here, simply use `tabs[0].url`. – wOxxOm Feb 23 '20 at 04:18

0 Answers0