Chrome App pushMessaging does not work when backgr

2019-06-08 09:52发布

问题:

manifest.json:

{
   "app": {
      "background": {
         "scripts": [ "background.js" ]
      }
   },
   "key": "...",
   "manifest_version": 2,
   "name": "Push Sample",
   "permissions": [ "notifications", "pushMessaging" ],
   "version": "1.0"
}

background.js:

chrome.runtime.onInstalled.addListener(
    function() {
        chrome.pushMessaging.onMessage.addListener(
            function (message) {
                chrome.notifications.create(
                    '',
                    {
                        type: 'basic',
                        iconUrl: 'icon24.png',
                        title: 'The Title',
                        message: message.payload
                    },
                    function (notificationID) {
                    }
                );
            }
        );
    }
);

That's the entire app. No HTML page (no window is created) and no other JavaScript.

When the background page is active, the app works fine, and I see the notification message popup at the upper right of my screen. (Not shown is some code I had in temporarily to show me the Channel ID, which my server uses. The server is a PHP program that uses Google Cloud Messaging for Chrome service. It seems to be OK.)

However, if I then do nothing for a few seconds, the app becomes inactive. On the Extensions page in Chrome, the line:

Inspect views: background page

changes to:

Inspect views: background page (Inactive)

When a message is sent then, that line changes to the active state ("background page", without the "(Inactive)" part, indicating the message has in some sense been received. However, the notification code does not result in a popup.

I can't determine what's wrong with logging, because when the JavaScript console is opened the app stays active, and then works.

Question: My app seems to be woken up when the message arrives, according to the status indication on the Extensions page, but it's not working. Anyone know why?

BUG FILED: Did a lot more testing, including with a stable (not beta) version of Chrome. Tried on OS X, Chrome OS, and Windows. Same thing. Here's the issue I filed: https://code.google.com/p/chromium/issues/detail?id=316315

回答1:

Sounds like a bug, file one at http://crbug.com/net and include the sample code. Update the question to link to the issue so others can star it to track the status.



回答2:

I misunderstood how event listening worked. Here's the info:

https://developer.chrome.com/apps/event_pages.html#registration

"Because the listeners themselves only exist in the context of the event page, you must use addListener each time the event page loads; only doing so at runtime.onInstalled by itself is insufficient."

Pointed out to me in a comment on the issue I filed. All is working now.