Sivabalan
Sivabalan

Reputation: 1131

Uncaught TypeError: OneSignal.once is not a function

Hai i want to sent the push notifcation to the browsers. So i used the 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");
    });
 });

But i am getting the Uncaught TypeError: OneSignal.once is not a function. If anyone knows about it please help me.

Upvotes: 6

Views: 11160

Answers (2)

Jason
Jason

Reputation: 6926

Solution

You'll need to wrap your call with OneSignal.push(function() { ... }):

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

Also, OneSignal.once('init') is not a valid event. The supported events are described here.

Explanation

The OneSignal SDK is loaded asynchronously on your page, e.g.:

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

You can read more about the async attribute here and here.

Basically, a script without an async attribute stops the loading of the rest of the page while it is fetched and executed, but async scripts allow the rest of the page to load, while it is eventually fetched and executed. This presents a problem for page scripts that depend on the OneSignal existing. If the OneSignal variable does not yet exist, how can OneSignal be used?

Most of the OneSignal code examples begin with:

var OneSignal = window.OneSignal || [];

This says: create a OneSignal variable, and if OneSignal is loaded already assign it to the loaded instance, otherwise let OneSignal equal the empty array [].

All arrays have a .push() function, so at this point, the OneSignal variable is simply an array of functions we're pushing on to it.

When the SDK finally loads, the SDK processes all the functions pushed so far and redefines .push().

Upvotes: 11

Shanmuga Sundaram
Shanmuga Sundaram

Reputation: 1

OneSignal.push(function() {
    OneSignal.once("init", function(event) {
        // This callback fires only once when the event occurs, and does not refire
    });
});

Upvotes: 0

Related Questions