1

I am trying to get the current tab url in chrome extension as per this answer. But the value of url remains always undefined. What could be the reason?

EDIT

Here is my code

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

I have defined the tabs permission in my manifest file

Community
  • 1
  • 1
Anonymous Platypus
  • 1,242
  • 4
  • 18
  • 47

3 Answers3

0

If you are trying to get url of current tab then there is no need for lastFocusedWindow.

I assume by current tab you mean current tab in current window.

More Info about current window : https://developer.chrome.com/extensions/windows#current-window

Use this code:

chrome.tabs.query({'active': true, 'currentWindow': true}, function (tabs) {
    var url = tabs[0].url;
});
Siddharth
  • 6,966
  • 2
  • 19
  • 34
0

I have solved the issue. This was an issue of variable scope. I have declared the variable as global outside the function, and then it worked.

var url;

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    url = tabs[0].url;
});
Anonymous Platypus
  • 1,242
  • 4
  • 18
  • 47
  • Are you trying to access the value of url outside the callback function? – Siddharth Jul 29 '15 at 10:22
  • 2
    This does not do anything at all. The `url` var local to the function has nothing to do with the `url` var in the global scope. You probably forgot to reload the extension after applying changes to manifest.json – Rob W Jul 29 '15 at 10:24
  • I edited the answer :) Forgot to delete the `var` part – Anonymous Platypus Jul 29 '15 at 12:00
0
"permissions": [
    "tabs",
    "bookmarks",
    "http://www.blogger.com/",
    "http://*.google.com/",
    "unlimitedStorage"
],

Add permissions in manifest.json.

dur
  • 15,689
  • 25
  • 79
  • 125
kathiresh
  • 1
  • 1
  • 2
    There are lots of unnecessary permissions here. Only the `tabs` permission is needed – Rob W Dec 26 '15 at 11:00
  • 2
    And the OP said `I have defined the tabs permission in my manifest file` So this is a low quality answer? – Danh Dec 26 '15 at 11:15