admin管理员组

文章数量:1323342

I am trying to create a quick Chrome extension (plete beginner) and just want to display an alert whenever the icon is clicked, so I tried the following:

manifest.json

{
    "name": "Something",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Woohoo",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "content_scripts" : [{
        "matches": ["<all_urls>"],
        "js" : ["bgscript.js"]
    }]

}

bgscript.js

chrome.browserAction.onClicked.addListener(function(tab) { 
    alert('icon clicked')
});

However when I click on my icon, nothing happens! Looking at the above - can anyone spot why this wouldn't work?

I am trying to create a quick Chrome extension (plete beginner) and just want to display an alert whenever the icon is clicked, so I tried the following:

manifest.json

{
    "name": "Something",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Woohoo",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "content_scripts" : [{
        "matches": ["<all_urls>"],
        "js" : ["bgscript.js"]
    }]

}

bgscript.js

chrome.browserAction.onClicked.addListener(function(tab) { 
    alert('icon clicked')
});

However when I click on my icon, nothing happens! Looking at the above - can anyone spot why this wouldn't work?

Share Improve this question asked Jan 17, 2014 at 13:35 wickywillswickywills 4,2143 gold badges40 silver badges55 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

In order to be notified for browser-action's onClicked event, you need a background-page (or better yet event-page), not a content-script.
Change your manifest like this:

// Replace that:
"content_scripts" : [{...}]

// with this:
"background": {
    "persistent": false,
    "scripts": ["bgscript.js"]
}

If you want the browser-action to invoke something on a content-script, you need to municate throught the background-page using Message Passing (e.g. Simple one-time requests).
E.g.:

manifest.json

{
    "name": "Something",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Woohoo",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },
    "content_scripts" : [{
        "matches": ["<all_urls>"],
        "js" : ["content.js"]
    }]
}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
    /* Send a message to the active tab's content script */
    chrome.tabs.sendMessage(tab.id, { action: 'saySomething' });
});

content.js

chrome.runtime.onMessage.addListener(function (msg) {
    /* We received a message, let's do as instructed */
    if (msg.action === 'saySomething') {
        alert('something');
    }
});

本文标签: javascriptVery simple Chrome Extension to display alertStack Overflow