0

In my Chrome extension I want to get current tab URL address. In my angular2 component I created string variable to save URL. Then I do this:

ngOnInit() {
    chrome.tabs.getCurrent(function(tab){
        this.currentUrl = tab.url;
    });
    console.log(this.currentUrl);
}

In the console I get the message undefined. So the question is how can I assign Chrome extension function result to my TypeScript variable?

Makyen
  • 31,849
  • 12
  • 86
  • 121
Nikas Žalias
  • 1,594
  • 1
  • 23
  • 51

1 Answers1

1

The chrome.tabs.getSelected() method is now deprecated.

The recommended way of getting the URL of the current tab is to use chrome.tabs.query().

An example usage:

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    var url = tabs[0].url;
});

This requires that you request access to the chrome.tabs API in your extension manifest:

"permissions": [ ...
   "tabs"
]

It's important to note that the definition of your "current tab" may differ depending on your extension's needs.

Setting lastFocusedWindow: true in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).

Setting currentWindow: true allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.

I chose to use lastFocusedWindow: true in this example, because Google calls out cases in which currentWindow may not always be present.

You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query

Ave
  • 4,338
  • 4
  • 40
  • 67