Desktop notifications from content scripts

前端 未结 2 1913
执念已碎
执念已碎 2020-12-29 14:47

I am trying to show a simple desktop notification code from a content script, but it doesn\'t seem to work.. I have added the permissions in the maifest.json file. Is there

相关标签:
2条回答
  • 2020-12-29 15:02

    Yes, notifications use Chrome specific API, and the content script is only valid for general javascript etc... The background page is where all chrome specific API's are capable of running... First you'll need to register your background page in the manifest.json file - like this:

     "background_page": "background.html",
    

    Also in the manifest file, Allow the required permissions:

    "permissions": [ "notifications" ],
    

    Then your script in the background page should look like this :

    <script>
    setTimeout("setNotification();",1); 
    function setNotification(){
      var n
      if (window.webkitNotifications.checkPermission() != 0){
        setNotification();
        return false;
      }
    n = window.webkitNotifications.createHTMLNotification('http://www.your-notification-address.com');
    n.show();}
    </script>
    
    0 讨论(0)
  • 2020-12-29 15:19

    You can't show notifications directly through a content script. But, you can show them through the background page.

    Your manifest.js should look something like this:

        {
         "name": "Notify This",
         "version": "0.1",
         "permissions": [
            "notifications"
         ],
         "background_page": "background.html",
         "content_scripts": [
           {
            "matches": ["http://www.example.com/*"],
            "js": ["contentscript.js"]
           }
         ]
        }    
    

    Then use the chrome.extension.sendRequest():

        // in your contentscript.js
        chrome.extension.sendRequest({msg: "Sup?"}, function(response) { // optional callback - gets response
            console.log(response.returnMsg);
        });
    

    And on the receiving end you should have a onRequest listener:

        // in your background.html
        chrome.extension.onRequest.addListener(
          function(request, sender, sendResponse) {
    
                // Create a simple text notification:
            var notify = webkitNotifications.createNotification(
              '48.png',  // icon url - can be relative
              'Hello!',  // notification title
              request.msg  // notification body text
            );
    
            notify.show();
    
            setTimeout(function(){ notify.cancel(); },5000);
            sendResponse({returnMsg: "All good!"}); // optional response
          });
    
    0 讨论(0)
提交回复
热议问题