Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!