由AddListener引起的循环

时间:2014-02-25 19:37:23

标签: javascript google-chrome-extension

我写了下面的代码。但是,有时它会起作用,有时会循环,有时根本不起作用。我究竟做错了什么?扩展应该从网页捕获消息,重定向然后将消息推送回content.js

chrome.runtime.onMessage.addListener(function(request, sender) {
    url = request.url;
    UName = request.username;
    PWord = request.password;
    chrome.tabs.update(sender.tab.id, {url: request.redirect});
    chrome.tabs.onUpdated.addListener(function doStuff(request) {   
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {message: "hello", username: UName, password: PWord}, function(response) {});
            chrome.tabs.onUpdated.removeListener(doStuff);
            return;
        });
    });
});

1 个答案:

答案 0 :(得分:1)

啊哈,我认为有一些代码冗余 也许,你可以尝试这样:

chrome.runtime.onMessage.addListener(function (request, sender) {
  var url = request.redirect;
  var name = request.username;
  var pwd = request.password;
  var ti = sender.tab.id; // cache the tabId

  chrome.tabs.update(ti, {url: url});
  chrome.tabs.onUpdated.addListener(function doStuff(tabId, changeInfo, tab) {
    if (tabId === ti && changeInfo.status === 'complete') {
      chrome.tabs.onUpdated.removeListener(doStuff);
      chrome.tabs.sendMessage(tabId, {message: "hello", username: name, password: pwd}, function (callbackData) {
        // TODO something
      });
    }
  });
});
祝你好运!