1

I'm working on an extension that requires the current tab url. I am able to access the correct url and alert it to the screen, but it isn't being recognized or able to be used elsewhere.

  var currentUrl;
  chrome.tabs.query({'currentWindow': true, 'active': true, 'lastFocusedWindow': true}, function (tabs) {
    alert(tabs[0].url);
       //this alerts correctly, but is the line 121 error in the error message
    var currentUrl = tabs[0].url;
       //this is undefined and can't be used
    });

This is the error message from the popup inspector: Error in response to tabs.query: TypeError: Cannot read property 'url' of undefined at Object.callback (chrome- extension://pokiconaaogmgmencihnokkdk/popup.js:121:23) at HTMLButtonElement. (chrome-extension://pokiconaaogmgmencihnokkdk/popup.js:120:19)

My permissions:

"permissions": [ "tabs", "storage" ],

Any ideas would be helpful, thank you.

  • The posted code isn't enough to diagnose the problem, but it contains a weird thing (a re-declaration of currentUrl) that makes me think you don't know the callback is asynchronous. See [How do I return the response from an asynchronous call?](//stackoverflow.com/q/14220321) and [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](//stackoverflow.com/q/23667086) – wOxxOm Sep 03 '18 at 20:00
  • thanks for the references, I will look at them until I can figure this out. I was trying to just duplicate what I say on another stackoverflow answer, which I thought had the callback in it already. https://stackoverflow.com/questions/1979583/how-can-i-get-the-url-of-the-current-tab-from-a-google-chrome-extension/14251218#14251218 chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) { var url = tabs[0].url; }); even this seems to break down for me, though – user3202390 Sep 03 '18 at 20:27
  • I've stripped the code block down to the basics and it still won't go: document.addEventListener('DOMContentLoaded', function() { var show = document.getElementById('show'); show.addEventListener('click', function(){ chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) { var url = tabs[0].url; alert(url); }); }); }); – user3202390 Sep 03 '18 at 20:34
  • 1
    Why do you use lastFocusedWindow? It can be e.g. devtools window which doesn't have tabs at all. Usually **only** `currentWindow` and `active` are used. – wOxxOm Sep 03 '18 at 20:36
  • this seems to have been the issue. Thank you! How can I move your answer up so later dummies like me can see it? – user3202390 Sep 03 '18 at 20:58
  • @wOxxOm You should put this as the answer - it was exactly my issue, I think I must have been using the same question/answer at the OP, which is this one: https://stackoverflow.com/a/14251218/399696 - the answer is in those comments too, but it would be good as an answer IMHO. – dmgig Sep 06 '18 at 15:46

0 Answers0