哪个window对象的getBackgroundPage()方法确实返回?

时间:2012-10-29 17:30:11

标签: google-chrome-extension return-value window-object

文档中的

,它说,getBackgroundPage()

  

返回运行后台页面的JavaScript“窗口”对象   在当前扩展名内。

是哪个窗口?它与我们得到的窗口相同:“chrome.windows.getCurrent()”。

1 个答案:

答案 0 :(得分:1)

如果您在manifest.json中指定了背景页面,则在您的扩展程序运行时该页面实际上是“已打开”(转到chrome://extensions并查找包含属性Inspect views: some_background_page.html的扩展程序) 。虽然您实际上看不到该页面,但它确实存在,并且正如文档所述,运行getBackgroundPage()将返回该页面的“窗口”对象,允许您在普通窗口上执行所有操作(请参阅here以获取其中一些属性/操作的列表。

要回答第二个问题,您可以阅读here当前窗口的值从后台页面调用时回退到上一个活动窗口。以下是可能有助于解释的示例background.js - 它将显示getCurrentgetAllinWindow的相同ID,这两个ID都将引用您调用的活动/可见页面中的页面扩展名 - 不是背景页本身:

//  This gets all current window tabs
chrome.tabs.getAllInWindow(null, function(tabs){
  // This alerts the window ID when getCurrent is called from background.js
  chrome.windows.getCurrent(function(window){
    alert("Background ID: " + window.id);
    });

  // Now we loop through the tabs returned by getAllInWindow,
  // showing the window ID. The ID is identical to the one above,
  // meaning that getCurrent (when called from a background page)
  // returns the current active window - NOT the background page
  chrome.windows.get(tabs[0].windowId, function(window) {
    alert("Active Window: " + window.id);
  });
});

希望有所帮助!

相关问题