开发者

Chrome extension, Javascript: getting URL from address bar

I have an extension that I am working on that has a "pop-up" putton on the bar,

I visit a sit开发者_C百科e (for example google.com) the button is pressed, I run this code in popup.html:

window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url;
  });
}

but instead of saving the google address, it saves it's own address like this: "chrome://extensions/".

How do I get it to save the last address instead of itself?


Your code shows the problem. getSelected returns the tab as a callback, which means the callback is executed when Chrome has found the selected tab. This is asynchronous, and is executed later:

window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  // 1) request selected tab
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url; // 3) selected tab is stored
  });
}


// 2) a tab is created
var saved_email = localStorage['blocker_user_email'];
if (saved_email === undefined ||  saved_email == "a@a.com")
{   
    //self.close();
    chrome.tabs.create({url: '0_register.html'});
} else{
      // self.close();
      chrome.tabs.create({url: '1_options.html'});
}

You could solve it by putting the second part of your code into the callback function:

window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url;

    var saved_email = localStorage['blocker_user_email'];
    if (saved_email === undefined ||  saved_email == "a@a.com")
    {   
        //self.close();
            chrome.tabs.create({url: '0_register.html'});
    } else{
          // self.close();
          chrome.tabs.create({url: '1_options.html'});
    }
  });
}

A callback function is a function you provide as an argument to another function (e.g. getSelected). When that other function has completed its task (e.g. find selected tab), it will execute the provided function. In the meantime, however, the code coming after the request will be executed regularly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜