0

I am writing an extension for Chrome but I am having an issue with updating a variable. I am trying to grab the URL and domain name and display them on the extension popup, but all that is being displayed is "[object HTMLDivElement]". I think this may be an issue of scope, but I am not sure why the global variables are not updated by the function below.

$(function() {
 var urlStr = "";
 var domain = "";
 urlStr = getURL();

 function getURL(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
   var activeTab = tabs[0];
   var url = activeTab.url;
   var urlParts = activeTab.url.replace('http://','').replace('https://','').split(/[/?#]/);
   domain = urlParts[0];
  });
  return url;
 }
  
  
  $('#pageURL').append('<h3>' + domain + '<h3>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="pageURL"></div>
  • Looks like `chrome.tabs.query` is asynchronous – Bergi Aug 04 '15 at 20:07
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Teepeemm Aug 04 '15 at 21:03

1 Answers1

1

chrome.tabs.query is asynchronous, so it will still be running when your $('#pageURL').append... line is executed. All you need to do is move that line in to the query callback:

$(function() {    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var activeTab = tabs[0];
        var domain = activeTab.url.replace(/http[s]?\:\/\//, '').split(/[/?#]/).shift();
        $('#pageURL').append('<h3>' + domain + '<h3>');
    });
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50