0

I'm trying to create a new tab, then execute a trivial code in it (i.e. an alert).
I'm using executeScript method for this programmatic Injection operation.
The tab is created successfully, but the alert is not displayed !

manifest.json

{
    "name" : "TabCreatorAlerter",
    "description" : "Opens a tab and shows an alert in it !",
    "version" : "1.0",
    "manifest_version" : 2,
    "background" : {
        "scripts" : ["background.js"],
        "persistent" : false
    },
    "permissions" : ["tabs"]
}

background.js

chrome.tabs.create(
    {url:"http://www.google.com"},
    function(createdTab) {
        chrome.tabs.executeScript(
            createdTab.id, 
            {code:"alert('hi');"} 
        );
    }
);

What is wrong with this code ? and how to fix it ?

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82

1 Answers1

1

You have to add the *://www.google.com/* permission to the manifest file.

If you look at your background page's console, you would have seen the error. Or, look at chrome.runtime.lastError in the callback of chrome.tabs.executeScript:

chrome.tabs.create(
    {url:"http://www.google.com"},
    function(createdTab) {
        chrome.tabs.executeScript(
            createdTab.id, 
            {code:"alert('hi');"},
            function() {
                if (chrome.runtime.lastError) {
                    alert(chrome.runtime.lastError.message);
                }
            }
        );
    }
);
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • The use of chrome.runtime.lastError which you provided is very helpful too, Thanks ! – Ashraf Bashir Nov 20 '13 at 16:13
  • I'm injecting code on a newly created tab as well, but the tab is an extension's page (with the url like: chrome-extension://fvdv...gdfg/page.html) but it is telling me that on the manifest I should add permission for that host. What should I add? so far I have permissions for ['contextMenus', 'tabs', '*://*/*'] – Alex Jun 29 '16 at 20:30
  • @Alex There is no permission to get access to the NTP if it is another extension page. – Rob W Jun 30 '16 at 06:26
  • Thank you Rob, so what error is it throwing and what am I supposed to do..? Cannot I inject code in a tab I created? – Alex Jun 30 '16 at 14:36
  • Is it *your* extension page? If so, use `chrome.extension.getViews` – Rob W Jun 30 '16 at 15:18