Jacob Waters
Jacob Waters

Reputation: 3

Javascript scope issue?

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>

Upvotes: 0

Views: 48

Answers (1)

Rob M.
Rob M.

Reputation: 36511

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>');
    });
}

Upvotes: 1

Related Questions