且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待一个异步方法的回调返回值?

更新时间:2021-10-15 08:25:54

也许的就可以解决通过跟踪标签URL的问题:

Maybe you can solve the problem by keeping track of the tab URLs?:


  1. 当应用程序启动时,通过获取所有打开的标签页网址 chrome.tabs.query

  2. 订阅 chrome.tabs.onUpdated chrome.tabs.onRemoved 添加/删除/更新URL当他们改变。

  1. When the app starts, get all open tab URLs by using chrome.tabs.query
  2. Subscribe to chrome.tabs.onUpdated and chrome.tabs.onRemoved and add/remove/update the URLs when they change.

某种code例子基础上,文档

Some kind of code example based on the documentation:

var tabUrlHandler = (function() {
   // All opened urls
   var urls = {},

   queryTabsCallback = function(allTabs) {
      allTabs && allTabs.forEach(function(tab) {
          urls[tab.id] = tab.url;
      });
   },

   updateTabCallback = function(tabId, changeinfo, tab) {
       urls[tabId] = tab.url;
   },

   removeTabCallback = function(tabId, removeinfo) {
       delete urls[tabId]; 
   };

   // init
   chrome.tabs.query({ active: true }, queryTabsCallback);
   chrome.tabs.onUpdated.addListener(updateTabCallback);
   chrome.tabs.onRemoved.addListener(removeTabCallback);

   return {
     contains: function(url) {
        for (var urlId in urls) {
           if (urls[urlId] == url) {
              return true;
           }
        }

        return false;
     }
   };

}());

现在你应该可以问 tabUrlHandler 直接在 onBeforeRequestMethod

Now you should be able to ask the tabUrlHandler directly in your onBeforeRequestMethod:

function onBeforeRequest(details) {
  var websiteAlreadyOpenInOtherTab = tabUrlHandler.contains(details.url);

  if (websiteAlreadyOpenInOtherTab) {
    return { cancel: true };
  }
}