1

I'm trying to make an extension that reloads a tab every 2 minutes, but I want it to try and reload even if the internet was offline (so it would reload when it went back on). Using location.reload() doesn't work when the window gives an error (e.g. offline), so I figured the best way was using chrome.tabs.reload().

The problem is, all chrome.tabs give me a similar error, if I try with an empty argument it should work, since it defaults to the current tab according to the documentation, but instead:

chrome.tabs.reload({});
Uncaught TypeError: Cannot call method 'reload' of undefined 

If I try to get the current tab ID:

chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
  console.log(tabs[0]);
});
Uncaught TypeError: Cannot call method 'query' of undefined 

And similarly, every single chrome.tabs has a similar error, "Cannot call xxyyzz of undefined". It's as if chrome couldn't see my tabs, what's going on?

My manifest.js is:

{
  "manifest_version": 2,

  "name": "test",
  "description": "",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "js": ["reload.js"],
      "run_at": "document_end"

    }
  ],
  "permissions": [
    "tabs","storage","http://www.google.com"
  ]
}
ShizukaSM
  • 343
  • 2
  • 5
  • 15
  • possible duplicate of [chrome.tabs returns undefined in content script](http://stackoverflow.com/questions/15034859/chrome-tabs-returns-undefined-in-content-script) – Rob W Mar 18 '13 at 15:24

1 Answers1

4

You cannot access chrome.tabs from inside a content script,

[...] content scripts have some limitations. They cannot:

  • Use chrome.* APIs (except for parts of chrome.extension) e.g chrome.tabs
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

[...]

You have to use a Background Page to use the chrome.tabs Api Methods.

And invoke reload from there.

Update:
I added a simple sample background.js which toggles Autoreloading for a tab (2 Minutes) through a contextmenu click. I tried to comment it as well as i can

Spoiler Warning: Do not click this link if you do this as a learning practice (or anything similar) for yourself otherwise feel free to do whatever you want with the code

Moritz Roessler
  • 8,542
  • 26
  • 51
  • Whoa, thanks a lot :) I actually had figured out a little bit before your last edit, but your solution worked beautifully and better than mine. Really thanks. – ShizukaSM Mar 18 '13 at 18:30
  • You're welcome =), I'm glad if I could help you on getting started with chrome extension development =) I wish you the best with future projects – Moritz Roessler Mar 18 '13 at 18:36