0

I am currently developing a chrome extension that can get cookies from a website, using chrome.getCookies. However, the url parameter in

chrome.getCookies 

must be a static url in order to work, like this:

chrome.cookies.get({url: 'https://example.org/#/', name: 
'token'}, function(cookie) {
    document.getElementById("token").innerHTML = cookie.value
});

But I want to make that url changed dynamically based on which tab I am using that extension. So I tried this:

var tabUrl;
chrome.tabs.getSelected(null, function(tab) {
    tabUrl = tab.url
});

chrome.cookies.get({url: tabUrl, name: 
'token'}, function(cookie) {
    document.getElementById("token").innerHTML = cookie.value
});

And it didn't work. What should I to to achieve my goal?

Edit: If anyone ever reach this page, here the solution, you have to put subsequent code inside the callback, here's the correct one:

chrome.tabs.getSelected(null, function(tab) {
    chrome.cookies.get({url: tab.url, name: 'expa_token'}, function(cookie) {
    document.getElementById("token").innerHTML = cookie.value
    });
});
manh.vu
  • 335
  • 1
  • 4
  • 14
  • Chrome extension API invokes its callbacks asynchronously so you need to put the subsequent code inside the callback. – wOxxOm May 29 '18 at 18:49
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – wOxxOm May 29 '18 at 18:50
  • Also `chrome.tabs.getSelected` is deprecated since Chrome 33, use [`chrome.tabs.query`](https://developer.chrome.com/extensions/tabs#method-query). [Example](https://stackoverflow.com/a/17826527/6586663). – Luka Čelebić May 29 '18 at 18:50
  • thanks @wOxxOm, I got it worked – manh.vu May 30 '18 at 03:45

0 Answers0