Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.windows undefined for Chrome Extension

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.

like image 336
Cameron Avatar asked Feb 26 '15 16:02

Cameron


1 Answers

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

 

like image 195
rgthree Avatar answered Oct 06 '22 21:10

rgthree