3

I want to create a new tab using Chrome Extension and when tab is loaded to show tab.id. Page is loaded but callback function is not worked (alert with tab.id is now showed).

The background.js file:

chrome.tabs.create({'url': 'http://www.google.com'}, function(tab){ alert(tab.id) })

The manifest.json file:

 {
     "name": "Test",
     "version": "1.0",
     "description": "Test plugin",
     "browser_action": {
         "default_popup": "popup.html",
         "default_icon":"icon.png"
     },
     "background": {
         "scripts": ["background.js"]
     },
     "manifest_version":2,
     "permissions": [
          "tabs",
          "http://*.facebook.com/*",
          "http://*.google.com/*",
          "storage"
     ]
}

The popup.html file:

<html>
  <head>
    <title>Test tabs</title>
  </head>
  <body>
    <script type="text/javascript" src=/background.js"></script>
  </body>
</html>

What can be a problem?

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132
shtkuh
  • 349
  • 1
  • 10
  • 22

3 Answers3

2

Your code must be located in background pages.

This is in the manifest.json file:

"background" : {"scripts" : ["background_script.js"] }

or

"background" : {"page" : "background_page.html" }

You need to use absolute path when you referring to the file inside background page:

<script type="text/javascript" src="/background.js"></script>
Xan
  • 74,770
  • 16
  • 179
  • 206
P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
0

I think callback function is executed in another context, and alert will not work. Try to open background page and DevTools and use console.log(tab.id) for see tab ID.

Yurii Kovalenko
  • 419
  • 3
  • 10
  • Can you please explain what is the "another context"? There are some restrictions of what callback function can do? – shtkuh Apr 03 '14 at 08:59
  • 1
    @shtkuh Chrome extensions scripts has 3 context of executing: -background scripts (wxecuting into extension)
    -content scripts ( can read and modify the DOM for the displayed web page)
    - injected scripts
    More info on [link](http://stackoverflow.com/questions/9915311/chrome-extension-code-vs-content-scripts-vs-injected-scripts)
    – Yurii Kovalenko Apr 03 '14 at 11:59
-1

Here's my solution:
chrome.tabs.create({url: URL, selected: false}, function(tab) { alert(tab.id) })

Not sure whether this is what you expected but the alert would work!