Home > Mobile >  How to access a variable in an asynchronous function(Chome.tab.query)
How to access a variable in an asynchronous function(Chome.tab.query)

Time:08-18

I would like to access the variable 'url' outside the chrome.tabs.query and edit my html file.

my js code:

chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
   url = tabs[0].url;
   
  alert(url)
  
  
});

Any ideas on how I could go about doing this?

CodePudding user response:

Use await for assigning url. Like,


async function getUrl() {

let url = await chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
   return tabs[0].url;
    
});

// code goes below

...

return
}

getUrl()

The reason why you can't get values in asynchronous function is that other code is already executed outside of asynchronous function which is executed earlier but still waits for values. Then you should make the asynchronous function finished first and then let codes execute later.

CodePudding user response:

If you want to access the url local variable outside of the scope of your arrow function, you can attach it to window. Add window.url = url; inside the arrow function. This is frowned upon and risky because some other script could overwrite the global variable, but if you're debugging it comes in handy.

  • Related