Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
chrome extension get number of open tabs

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

    });
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda