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>

2

1 Answer 1

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>');
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should omit that urlStr and return url then as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.