Sunday, 15 January 2017

javascript - How to wait for an asynchronous method's callback return value?

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



  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.


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;
}
};
}());

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 };
}
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...