【问题标题】:Google Cloud Messaging for Chrome - a received message is not shown as a popup适用于 Chrome 的 Google Cloud Messaging - 收到的消息未显示为弹出窗口
【发布时间】:2014-06-01 06:16:42
【问题描述】:

我下载了 Google push-sample-app code,从清单中删除了密钥,将应用上传到 Chrome 网上应用店,然后从网上应用店将其安装到 Chrome 中。

现在 chrome://extensions/ 将该应用列为“已启用”,并带有“检查视图:背景页面(非活动)”。 Chrome 任务管理器不会将应用列为当前正在运行。

如果在 chrome://extensions/ 选项卡上,我单击“Push Messaging Sample”应用程序的“background page (Inactive)”链接,然后显示检查视图在单独的 Chrome 窗口中打开,Chrome 任务管理器中会出现一个新条目:“后台页面:推送消息示例”。只要检查视图 Chrome 窗口打开,事件页面“background.js”就不会被卸载。当消息被发送到推送消息服务时,会出现一个带有消息文本的弹出窗口。

如果我关闭检查视图 Chrome 窗口,并向推送消息服务发送消息,Chrome 任务管理器会显示事件页面“background.js”被加载,然后在几秒钟内从任务管理器中消失。但是,不会出现带有消息的弹出窗口。

如何更改此应用以在不运行任何额外 Chrome 窗口的情况下显示弹出消息?

【问题讨论】:

    标签: google-chrome google-cloud-messaging google-chrome-app chrome-gcm


    【解决方案1】:

    示例应用程序不会显示来自“后台页面处于非活动状态”状态的通知,因为当后台页面被唤醒时,chrome.pushMessaging.onMessage 的事件处理程序未设置。

    当用户通过单击其图标启动应用程序时,会触发 chrome.app.runtime.onLaunched() 事件。但是当后台页面由于一些传入事件(如推送消息或警报)而被激活时,不会触发 onLaunched - 相反,仅执行“初始脚本”,即函数之外的 JS 代码。后台页面的初始脚本必须注册事件侦听器,以便在初始加载后 Chrome 知道要调用哪个处理程序。示例应用仅在 onLaunched 中注册 onMessage 处理程序,而不是从初始脚本中注册。

    “修复”示例应用程序很容易 - 只需将 setupPush() 调用从 onLaunched() 处理程序移至 background.js 文件的最后:

    background.js:

    ....
    // When a Push Message arrives, show it as a text notification (toast)
    function showPushMessage(payload, subChannel) {
      var notification = window.webkitNotifications.createNotification(
          'icon.png', 'Push Message',
          "Push message for you! " +
          payload +" [" + subChannel + "]");
      notification.show();
    }
    
    setupPush();  // <-- this executes every time page loads, not only in onLaunched
    

    这将导致 setupPush() 在每次激活后台页面时执行,无论是用户启动应用程序还是应用程序在后台启动以响应传入的推送消息。

    【讨论】:

      【解决方案2】:

      question / answer 解释了缺少的内容:

      “因为监听器本身只存在于事件页面的上下文中,所以每次事件页面加载时都必须使用addListener;仅在runtime.onInstalled时自己使用是不够的。”

      要修复push-sample-app,只需添加到background.js

      // Register with the Push Messaging system for the Push Message.
      chrome.pushMessaging.onMessage.addListener(messageCallback);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-14
        • 1970-01-01
        • 2022-06-14
        • 2018-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        相关资源
        最近更新 更多