How do I get the window object for a specific tab if I have that tab's tabId?
12,815
Solution 1
To get the DOM window object from a tabId, you should insert a content script in that tab:
chrome.tabs.executeScript(tabId, {code:'var w = window; console.log(w);'});
https://developer.chrome.com/extensions/tabs#method-executeScript
Perhaps you'll need to comunicate with your background page:
https://developer.chrome.com/extensions/content_scripts#host-page-communication
Solution 2
The window object as seen inside chrome extensions:
chrome.tabs.get(YOUR_TAB_ID_HERE, function(tab){
chrome.windows.get(tab.windowId, function(win){
console.log(win); // THIS IS THE WINDOW OBJECT
});
});
But if you need the javascript runtime inside a specific tab, you'll need to use Content Scripts which are better explained here:
http://code.google.com/chrome/extensions/content_scripts.html
Author by
trusktr
Joe Pea trusktr.io (personal site) lume.io (open source 3D toolkit I'm working on) twitter github codepen
Updated on June 15, 2022Comments
-
trusktr almost 2 years
I have the tabId of a tab. How do I get it's window object?
-
Can't Tell almost 12 yearsCan you tell what you are trying to achieve? Because there may be a different approach to get it done?
-
trusktr almost 12 yearsI have the tabId of a tab. How do I get it's window object?
-
-
trusktr almost 12 yearsWait, is "win" the window object of a view, or the window object of a window that contains multiple tabs? I'm trying to get the window object of a view.
-
Silviu-Marian almost 12 years
win
is the window which contains tabs. To get the other one, you need content scripts, so read the link I gave you. You'll have to inject some javascript from extension into the tab. It's a bit tricky but you'll get it though. -
qwerty almost 10 yearsThis makes no sense. This will just log the window object to the console and copy it to another variable. It doesn't return anything.
-
runfaj over 8 yearsThis answer is completely useless unless you add a callback. Something like so: chrome.tabs.executeScript( null, {code:"var w = window; w"}, function(results){ console.log(results[0]); } ); However, due to security, many of the window items are unavailable, so you'll still have to use the content script/message passing api in order to do anything functional.