简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM