GCM to Chrome. General help. Unable to subscribe / no sender id

那年仲夏 提交于 2019-12-11 20:34:12

问题


So I'm working in VS2013 with .NET and I'm trying to figure out how to get Cloud Messaging(GCM) working for Chrome.

What I want is to have it working like this sample: https://simple-push-demo.appspot.com/

So I dont wanna have to work with Android, it just has to work like the sample above where it works in Chrome without having to install an extension/webapp in Store. I've tried many samples and guides and tried changing it but I can't get anything to work.

Atm. I'm using this sample code: https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications

But I get two error messages:

1: "Unable to subscribe to push"

2: "AbortError: Registration failed – no sender id provided."

I know the sender id = project number in Google Console and the API keys are under Credentials – I have tried multiple times with both Server API key and Browser API key. Also Cloud Messaging API for Chrome and Android are enabled.

Manifest.json

{
 "name": "Push Demo",
 "short_name": "Push Demo",
 "manifest_version": 2,
 "version": "0.0.0.3",
 "browser_action": {
 "default_icon": "images/icon-192x192.png"
  },
 "display": "standalone",
 "permissions": [
    "gcm",
    "storage"
  ],
 "gcm_sender_id": "94512349348",
 "gcm_user_visible_only": true
}

In "chrome://serviceworker-internals" it shows as registered and when I try a push it says:

"Console: {"lineNumber":4,"message":"Received a push message","message_level":1,"sourceIdentifier":3,"sourceURL":"localhost:4724/service-worker.js"}"

I cannot get it to subscribe. Whenever it goes into the function subscribe() it always ends up telling me "unable to subscribe" and that it's probably a wrong sender ID or gcm_user_visible_only - which I fail to understand since I'm sure I have entered the right info.

Some code from Main.js

function subscribe() {
    // Disable the button so it can't be changed while
    // we process the permission request`enter code here`
    var pushButton = document.querySelector('.js-push-button');

pushButton.disabled = true;

navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
    serviceWorkerRegistration.pushManager.subscribe({ userVisibleOnly: true })
      .then(function (subscription) {
          // The subscription was successful
          isPushEnabled = true;
          pushButton.textContent = 'Disable Push Messages';
          pushButton.disabled = false;

          return sendSubscriptionToServer(subscription);
      })
      .catch(function (e) {
          if (Notification.permission === 'denied') {
              window.Demo.debug.log('Permission for Notifications was denied');
              pushButton.disabled = true;
          } else {
              // A problem occurred with the subscription, this can
              // often be down to an issue or lack of the gcm_sender_id
              // and / or gcm_user_visible_only
              window.Demo.debug.log('Unable to subscribe to push.', e);
              pushButton.disabled = false;
              pushButton.textContent = 'Enable Push Messages';
          }
      });
});

function initialiseState() {
    // Are Notifications supported in the service worker?
    if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
        window.Demo.debug.log('Notifications aren\'t supported.');
        test.textContent = test.textContent + ' Notifications not supported; ';
        return;
    }
    test.textContent = test.textContent + ' initState; ';
    // Check the current Notification permission.
    // If its denied, it's a permanent block until the
    // user changes the permission
    if (Notification.permission === 'denied') {
        window.Demo.debug.log('The user has blocked notifications.');
        test.textContent = test.textContent + ' DENIED; ';
        return;
    }

    // Check if push messaging is supported
    if (!('PushManager' in window)) {
        window.Demo.debug.log('Push messaging isn\'t supported.');
        return;
    }

    // We need the service worker registration to check for a subscription
    navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
        // Do we already have a push message subscription?
        serviceWorkerRegistration.pushManager.getSubscription()
          .then(function (subscription) {
              // Enable any UI which subscribes / unsubscribes from
              // push messages.
              var pushButton = document.querySelector('.js-push-button');
              pushButton.disabled = false;

              if (!subscription) {
                  // We aren’t subscribed to push, so set UI
                  // to allow the user to enable push

                  return;
              }

              // Keep your server in sync with the latest subscription
              sendSubscriptionToServer(subscription);

              // Set your UI to show they have subscribed for
              // push messages
              pushButton.textContent = 'Disable Push Messages';
              isPushEnabled = true;
          })
          .catch(function (err) {
              window.Demo.debug.log('Error during getSubscription()', err);
          });
    });
}

Service-worker.js

'use strict';

self.addEventListener('push', function (event) {
    console.log('Received a push message', event);

    var title = 'Yay a message.';
    var body = 'We have received a push message.';
    var icon = '/images/icon-192x192.png';
    var tag = 'simple-push-demo-notification-tag';

    event.waitUntil(
      self.registration.showNotification(title, {
          body: body,
          icon: icon,
          tag: tag
      })
    );
});


self.addEventListener('notificationclick', function (event) {
    console.log('On notification click: ', event.notification.tag);
    // Android doesn’t close the notification when you click on it
    // See: http://crbug.com/463146
    event.notification.close();

    // This looks to see if the current is already open and
    // focuses if it is
    event.waitUntil(clients.matchAll({
        type: "window"
    }).then(function (clientList) {
        for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
            if (client.url == '/' && 'focus' in client)
                return client.focus();
        }
        if (clients.openWindow)
            return clients.openWindow('/');
    }));

});

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="description" content="Sample illustrating the use of Push Messaing and Notifications.">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Push Messaging &amp; Notifications</title>

    <!-- Include manifest file in the page -->
    <link rel="manifest" href="manifest.json">

</head>

<body>
    <h1>Push Messaging &amp; Notifications</h1>

    <p>Available in <a href="http://www.chromestatus.com/feature/5416033485586432">Chrome 42+</a> &amp; <a href="http://www.chromestatus.com/feature/5480344312610816">Chrome 42+</a></p>

    <p>To use this sample please do the following:</p>


    <p>
        <button class="js-push-button" disabled>
            Enable Push Messages
        </button>
    </p>

    <br />
    <br />

    <h2>cURL Command to Send Push</h2>
    <div class="js-curl-command"></div>

    <br />
    <br />
    <h3>Test</h3>
    <div class="test"></div>

    <script src="config.js"></script>
    <script src="demo.js"></script>
    <script src="main.js"></script>
</body>
</html>

So what am I doing wrong?

Am I using the completely wrong sample or is there something I'm completely missing?

  • In short; any help will be greatly appreciated.

回答1:


So this isn't really an answer, but it works for me after I fixed some unrelated issues with the code (you did not provide all the code). I temporarily put it online here: https://sandbox.aykevl.nl/gcm-stackoverflow/.

You should check whether manifest.json is properly loading, I suspect it isn't. Check Chrome DevTools for that.
EDIT: from the comments: apparently manifest.json is loaded with the wrong MIME-type. This was set up correctly in my webserver (Nginx) but not in the webserver of the asker (IIS). According to the specification, it has to be application/manifest+json but in Chrome application/json works too.

Additionally, you can remove some stuff from mainfest.json. It is not a Chrome app, so things like "browser_action", "manifest_version" and "permissions" are unnecessary. Read the specification if you want to know what goes in the manifest. It shouldn't matter, but it is confusing.

Suggestions for next time:

  • Use a standard way of logging. I don't know what window.Demo.debug is, but there's console.log, console.warn and console.error.
  • Preferably, put it online somewhere next time so it is easier to debug. There are close relations between the files and somewhere that goes wrong. You are much more likely to get an answer when it is easy to see what the problem is.



回答2:


Make sure manifest file is accessible (no authorization required to access it).

Or try add crossorigin="use-credentials" to <link> tag with manifest. This is need for request manifest with auth cookies and auth headers.




回答3:


Just add <link rel="manifest" href="/static/manifest.json"> under s style tag.

Where href value is path to your manifest.json file



来源:https://stackoverflow.com/questions/30782247/gcm-to-chrome-general-help-unable-to-subscribe-no-sender-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!