【问题标题】:Uncaught TypeError: OneSignal.once is not a function未捕获的 TypeError:OneSignal.once 不是函数
【发布时间】:2016-11-21 22:46:24
【问题描述】:

嘿,我想向浏览器发送推送通知。所以我使用了onesignal。

var OneSignal = OneSignal || [];
OneSignal.push(["init", {
    appId           :   "xxxxxxx",
    autoRegister    :   false, /* Set to true to automatically prompt visitors */
    subdomainName   :   "https://foxtaxi.onesignal.com",
    notifyButton    :   {
        enable: true /* Set to false to hide */
    }
}]);

OneSignal.push(function() {
    OneSignal.once("init", function(event) {
        alert("hhh");
    });
 });

但我得到了 Uncaught TypeError: OneSignal.once is not a function。如果有人知道,请帮助我。

【问题讨论】:

    标签: javascript push-notification onesignal


    【解决方案1】:

    解决方案

    您需要使用OneSignal.push(function() { ... }) 结束通话:

    OneSignal.push(function() {
      /* ... */
    });
    

    另外,OneSignal.once('init') 不是有效事件。 supported events are described here

    说明

    OneSignal SDK 在您的页面上异步加载,例如:

    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async"></script>
    

    您可以阅读有关异步属性herehere 的更多信息。

    基本上,没有async 属性的脚本在获取和执行时会停止加载页面的其余部分,但async 脚本允许加载页面的其余部分,而最终 获取并执行。这对依赖于现有 OneSignal 的页面脚本提出了问题。如果OneSignal变量还不存在,那OneSignal怎么用?

    大部分 OneSignal 代码示例都以:

    var OneSignal = window.OneSignal || [];
    

    这里说:创建一个 OneSignal 变量,如果加载了 OneSignal 已经把它赋值给加载的实例,否则让 OneSignal 等于空数组[]

    所有数组都有一个.push() function,所以此时,OneSignal 变量只是我们正在向其推送的函数数组。

    当 SDK 最终加载时,SDK processes all the functions pushed so far and redefines .push()

    【讨论】:

    • 嗨,杰森。感谢您的回答。现在我没有得到那个控制台错误。但是当我在初始化函数上发出警报时,我没有收到那个警报消息。我已经更改了参考代码。
    【解决方案2】:
    OneSignal.push(function() {
        OneSignal.once("init", function(event) {
            // This callback fires only once when the event occurs, and does not refire
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 2019-09-26
      • 2015-12-29
      • 2021-09-09
      • 2017-07-31
      • 2016-11-02
      • 2016-08-07
      • 2022-01-25
      • 2021-03-13
      相关资源
      最近更新 更多