Michael R
Michael R

Reputation: 33

Chrome Extension: How do I get current tabs title and assign string to variable?

I am trying to get the title of the current tab in chrome using an extension and then assigning the returned string to a variable. I managed to get the title using tabs[0].title but I haven't been able to assign that title to a new string variable.

This is the code:

var address;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    var title = tab.title;

    console.log("Title: " + title);
    address = title;
});

console.log("Address:" + address);

The line console.log("Title: " + title); shows that tab.title is working as expected, however, when I try to assign the title string to a new variable (address) it is not working shown when the line console.log("Address:" + address); returns "Address:Undefined".

I have also tried creating the variable address as an empty string in the first line. This looks like: var address = new String();

I have looked on here and looked at the documentation and couldn't find an answer to the problem I am having.

Upvotes: 3

Views: 1321

Answers (1)

Aefits
Aefits

Reputation: 3469

You will need to use a callback function. See below the example.

var address;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    var title = tab.title;

    console.log("Title: " + title);
    address = title;
    print_address(address);
});

function print_address(address) {
    console.log("Address:" + address);
}

Upvotes: 1

Related Questions