最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - chrome.windows undefined for Chrome Extension - Stack Overflow

programmeradmin0浏览0评论

I'm building a Chrome extension that allows the user to manage open tabs for an application (website). The manifest is:

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

But when I do this in the main.js file:

console.log(chrome.windows);

I get undefined in the console... Any ideas why? I have both tabs and activeTab as permissions and the extension is being run in the developer mode.

I'm building a Chrome extension that allows the user to manage open tabs for an application (website). The manifest is:

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

But when I do this in the main.js file:

console.log(chrome.windows);

I get undefined in the console... Any ideas why? I have both tabs and activeTab as permissions and the extension is being run in the developer mode.

Share Improve this question edited Feb 26, 2015 at 16:51 Sarah Elan 2,4611 gold badge25 silver badges45 bronze badges asked Feb 26, 2015 at 16:30 CameronCameron 28.8k102 gold badges288 silver badges490 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

chrome.windows will not be available in your main.js because it is an injected content script.

Only your background/event pages JavaScript has access to chrome.windows. You will need to use message passing from your content script to your background script to trigger the window actions you want.

For instance, to create a window from an content script, your extension may look something like this:

Manifest:

{
  ...
  "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);
    });
  }
});

 

发布评论

评论列表(0)

  1. 暂无评论