如果我有特定选项卡的 tabId,如何获取该选项卡的窗口对象

How do I get the window object for a specific tab if I have that tab's tabId?

本文关键字:选项 获取 对象 窗口 何获取 如果 tabId      更新时间:2023-09-26

我有一个选项卡的tabId。如何获取它的窗口对象?

在 chrome 扩展中看到的窗口对象:

 chrome.tabs.get(YOUR_TAB_ID_HERE, function(tab){
      chrome.windows.get(tab.windowId, function(win){ 
           console.log(win); // THIS IS THE WINDOW OBJECT
      });
 });

但是,如果您需要特定选项卡中的javascript运行时,则需要使用内容脚本,此处可以更好地解释:

http://code.google.com/chrome/extensions/content_scripts.html

要从 tabId 获取 DOM 窗口对象,您应该在该选项卡中插入内容脚本:

chrome.tabs.executeScript(tabId, {code:'var w = window; console.log(w);'});

https://developer.chrome.com/extensions/tabs#method-executeScript

也许您需要与背景页面进行通信:

https://developer.chrome.com/extensions/content_scripts#host-page-communication