1

I am trying to create a google chrome extension that gets the url of the website you are on and parses the info. I am using chrome.tabs.query, however I am having some trouble with the results as it seems like everything is running asynchronously. I am receiving the console logs from the second function before the first one. Here is my code:

function getURL(){ //Gets the current URL
  var firsturl;
  chrome.tabs.query({
    'active': true,
    'windowId': chrome.windows.WINDOW_ID_CURRENT
    }, function (tabs) {
      var temp = tabs[0].url;
      console.log(temp)
      firsturl = temp;
      console.log(firsturl)
      });
      return firsturl;
}

function parseURL(){  //This function parses the URL and leaves us with the Website name
  var url = getURL(); //Get the URL
  console.log(url);
  var parser = document.createElement("a"); 
  parser.href = url;  //Pass URL to parser


  var host = parser.hostname; //Grab hostname from URL ex."http://www.google.com" ---> "google.com"

  console.log(host);

  host = host.replace(/^www\./,'').split('.').slice(0,-1).join('.');
  
  console.log(host);

  return host;
}
Turtily
  • 11
  • 2
  • You need to stick with the asynchronous pattern, so either pass a call back function to your `getURL` function, which should be called when the URL is known, or convert your code to use promises (where you can use `async` `await` syntax). – trincot Jul 15 '20 at 18:28

0 Answers0