GCM 至 Chrome。一般帮助。无法订阅/没有发件人 ID

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

所以我在 VS2013 中使用 .NET 工作,我试图弄清楚如何让云消息 (GCM) 为 Chrome 工作。

我想要的是让它像这个示例一样工作:https://simple-push-demo.appspot.com/

所以我不想使用 Android,它只需要像上面的示例一样工作,它在 Chrome 中工作而无需 在商店中安装 extension/webapp。 我尝试了很多示例和指南并尝试对其进行更改,但我什么也做不了。

大气压。我正在使用这个示例代码: https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications

但我收到两条错误消息:

1: "Unable to subscribe to push"

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

我知道 Google 控制台中的发件人 ID = 项目编号,API 密钥在凭据下 – 我已经多次尝试使用服务器 API 密钥和浏览器 API 键。 Chrome 和 Android 的云消息 API 也已启用。

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
}

在 "chrome://serviceworker-internals" 中它显示为已注册,当我尝试推送时它说:

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

我无法订阅它。每当它进入函数 subscribe() 时,它总是最终告诉我 "unable to subscribe" 并且它可能是错误的发件人 ID 或 gcm_user_visible_only - 我无法理解,因为我确定我输入了正确的信息。

一些代码来自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);
          });
    });
}

服务-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>

那我做错了什么?

我是否使用了完全错误的样本,或者我完全遗漏了什么?

确保清单文件可访问(无需授权即可访问)。

或尝试将 crossorigin="use-credentials" 添加到带有清单的 <link> 标签。这是需要带有 auth cookies 和 auth headers.

的请求清单

所以这并不是一个真正的答案,但在我修复了一些与代码无关的问题后它对我有用(你没有提供所有代码)。我暂时放在网上:https://sandbox.aykevl.nl/gcm-Whosebug/.

您应该检查 manifest.json 是否正确加载,我怀疑不是。为此检查 Chrome DevTools。
编辑:来自评论:显然 manifest.json 加载了错误的 MIME 类型。这是在我的网络服务器 (Nginx) 中正确设置的,但在提问者 (IIS) 的网络服务器中没有正确设置。根据 the specification,它必须是 application/manifest+json 但在 Chrome application/json 中也可以。

此外,您可以从 mainfest.json 中删除一些内容。如果您想知道清单中的内容,那是 而不是 Chrome app, so things like "browser_action", "manifest_version" and "permissions" are unnecessary. Read the specification。应该没关系,但很混乱。

下次建议:

  • 使用标准的日志记录方式。我不知道 window.Demo.debug 是什么,但是有 console.logconsole.warnconsole.error
  • 最好下次把它放在网上的某个地方,这样更容易调试。文件和出错的地方之间有密切的关系。如果很容易看出问题所在,您就更有可能得到答案。

只需在 style 标签下添加 <link rel="manifest" href="/static/manifest.json">

其中 href 值是 manifest.json 文件的路径