Alex
Alex

Reputation: 1055

Trigger Chrome extension notifications from content script

I currently am trying to make it so my extension will show a notification when called on to do so.

When the icon is clicked, background.js executes a script into the page. This is what my background.js file looks like:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null,{file: "buy.js"});
  }
);

chrome.extension.onRequest.addListener(
  function (request, sender, sendResponse) {
    var notify = webkitNotifications.createNotification(
      'face.png',
      'Item Sniped!',
      'Item sniper sniped an item!'
    );
    notify.show();
  }
);

And yes, I did set up all of the permissions in manifest.json. My manifest file:

{
   "manifest_version": 2,
   "name": "Sniper",
   "version": "1.5",
   "description": "Sniper",
   "browser_action": {
     "default_icon": "face.png",
     "default_title": "Limited Sniper"
   },
   "background": { "scripts": ["background.js"] },
   "permissions": [
     "notifications",
     "tabs",
     "http://*/*"
   ]
}

I know that I need to have a listener in my background.js file, but is it even possible to send a request from buy.js (The script that is executed) to background.js to make the notification?

Upvotes: 2

Views: 3233

Answers (1)

Hank X
Hank X

Reputation: 2044

yes. content scripts can not do something. see here

so you have to send a request to background.js to make the notification. and, if your notification has a icon, rememmber to regist it in you manifest.json:

 "web_accessible_resources":["face.png"]

However, content scripts have some limitations. They cannot: Use chrome.* APIs (except for parts of chrome.extension) Use variables or functions defined by their extension's pages Use variables or functions defined by web pages or by other content scripts

Upvotes: 3

Related Questions