I'm writing an extension that has a button with different functions. So I'm trying to figure out how to retrieve number of tabs that are open and in my content.js I want to execute different thing when clicking the button depending on how many tabs that are open.
Been trying different approaches with chrome.tabs.query in background.js and sending it back but having troubles since it's asynchronous.
content.js
if (tabcount < 2) {
$(function () {
$("#Back").on('click', function (e) {
e.preventDefault();
window.history.back();
});
});
console.log("one tab");
}
if (tabcount > 1) {
$(function () {
$("#Back").on('click', function (e) {
e.preventDefault();
window.location.href = 'exit';
});
});
console.log("more tabs");
}
Edit: added message code
Background message code
function sendMessageToTab(tabId, message) {
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, message, resolve)
})
}
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({ windowType: 'normal' }, function (tabs) {
const msg = tabs.length;
sendMessageToTab(tabs[0].id, msg)
});
} return true;
});
content recieve
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request > 1) {console.log('more than 1 tab open'); }
});