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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10822133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:09:51  来源:igfitidea点击:

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

javascripthtmlgoogle-chromegoogle-chrome-extension

提问by trusktr

I have the tabId of a tab. How do I get it's window object?

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

回答by Silviu-Marian

The window object as seen inside chrome extensions:

在 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
      });
 });

But if you need the javascript runtime inside a specific tab, you'll need to use Content Scripts which are better explained here:

但是,如果您需要特定选项卡内的 javascript 运行时,您将需要使用内容脚本,这里有更好的解释:

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

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

回答by Alejandro Silvestri

To get the DOM window object from a tabId, you should insert a content script in that tab:

要从 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/tabs#method-executeScript

Perhaps you'll need to comunicate with your background page:

也许您需要与您的背景页面进行交流:

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

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