chrome.windows Chrome 扩展未定义

chrome.windows undefined for Chrome Extension

我正在构建一个 Chrome 扩展程序,允许用户管理应用程序(网站)的打开选项卡。清单是:

{
    "manifest_version": 2,
    "name": "AT Tabs",
    "version": "0.1",
    "permissions": ["activeTab", "tabs"],
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["main.js"]
    }]
}

但是当我在 main.js 文件中这样做时:

console.log(chrome.windows);

我在控制台中得到 undefined ...有什么想法吗?我同时拥有选项卡和 activeTab 作为权限,并且扩展程序在开发人员模式下 运行。

chrome.windows 在您的 main.js 中将不可用,因为它是一个注入的内容脚本。

只有从内容脚本到后台脚本的 background/event pages JavaScript has access to chrome.windows. You will need to use message passing 才能触发您想要的 window 操作。

例如,要从内容脚本创建 window,您的扩展可能如下所示:

清单:

{
  ...
  "background": {
    "scripts": ["eventPage.js"],
    "persistent": false
  },
  ...
}

main.js:

chrome.runtime.sendMessage({
    action: 'createWindow',
    url: 'http://google.com'
  },
  function(createdWindow) {
    console.log(createdWindow);
  });

eventPage.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request && request.action === 'createWindow' && request.url) {
    chrome.windows.create({url: request.url}, function (win) {
      sendResponse(win);
    });
  }
});