Stepan Yakovenko Stepan Yakovenko - 4 months ago 25
Javascript Question

Get window id from javascript with help of chrome extension

Currently I send message from my html page to chrome extension and it, in turn calls

chrome.windows.getCurrent(function (win) {
callback(win.id)
});


to get window Id. But if user selects another (or opens new) window just before this call, I get incorrect id. How can I get id of window, where my js code is running?

Answer

In your background script, you probably use chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){ ... }

In that listener, you can use sender.tab.windowId to get the Id of the window that sent the message to the background script, regardless of the current active window.