safe_malloc
safe_malloc

Reputation: 886

How to get the active tab in last focused non-extension window?

I am developing an extension which uses a service worker. The service worker opens a popup window using the usual chrome.windows.create(). During development I have 2 chrome windows open, lets call them A & B. A has tabs of various sites. B has tabs for testing my extension.

Now with a tab in focus in B, I click my extension icon on the toolbar which causes my extension to launch its own window, say C, as discussed above. So there are now in total 3 windows open.

In my extension I want to find the tab id of the active tab in B as that's what was I was focused on when I clicked the extension icon. The following however gives me the tab id of the single tab in C which is my extension's popup

async function getTabId() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    console.log(tab)
    console.log(tab.title);
    return tab.id;
}

Which is fine as I passed lastFocusedWindow: true. So I pass lastFocusedWindow: false , but that gives me the last focused tab in A!

How do I get the last focused tab in B which was the actual non-extension window in focus before my chrome extension launched its popup?

Upvotes: 2

Views: 477

Answers (1)

woxxom
woxxom

Reputation: 73516

You can get the active tab before opening the new tab and pass the id via URL:

// background script
(async () => {
  const [activeTab] = await chrome.tabs.query({active: true, currentWindow: true});
  const params = new URLSearchParams({tabId: activeTab?.id});
  const newTab = await chrome.tabs.create({url: 'mypage.html?' + params});
})();
// mypage.js
const tabId = +new URLSearchParams(location.search).get('tabId');

Upvotes: 1

Related Questions