Skip to content
This repository has been archived by the owner on Sep 4, 2020. It is now read-only.

Hello, i am developing a cordova app which requires push notifications to be sent to users android phone, so i tried using this new phonegap push plugin as old one is deprecated, and it keeps giving me an error in console: Uncaught ReferenceError: module is not defined --- Line 154 Push.js and i dont have much experience with cordova, so can anyone assist me ? #128

Closed
pOoOf opened this issue Sep 12, 2015 · 13 comments

Comments

@pOoOf
Copy link

pOoOf commented Sep 12, 2015

// i am using Code
var app = {
        initialize: function() {
            this.bindEvents();
        },
        bindEvents: function() {
            document.addEventListener("deviceready", this.__onDeviceReady, false);
        },
        __onDeviceReady: function() {
            checkConnection();
            var push = PushNotification.init({
                "android": {
                    "senderID": "123456789",
                    "sound": true,
                    "vibrate": true
                },
                "ios": {}, 
                "windows": {} 
            });

            push.on('registration', function(data) {
                console.log("registration event");
                document.getElementById("regId").innerHTML = data.registrationId;
                console.log(JSON.stringify(data));
            });

            push.on('notification', function(data) {
                console.log("notification event");
                console.log(JSON.stringify(data));
                var cards = document.getElementById("cards");
                var push = '<div class="row">' +
                      '<div class="col s12 m6">' +
                      '  <div class="card darken-1">' +
                      '    <div class="card-content black-text">' +
                      '      <span class="card-title black-text">' + data.title + '</span>' +
                      '      <p>' + data.message + '</p>' +
                      '    </div>' +
                      '  </div>' +
                      ' </div>' +
                      '</div>';
                cards.innerHTML += push;
            });
            push.on('error', function(e) {
                console.log("push error");
            });
        }
    };

    app.initialize();
@pOoOf pOoOf changed the title Hello, i am developing a cordova app which requires push notifications to be sent to android app Hello, i am developing a cordova app which requires push notifications to be sent to users android phone, so i tried using this new phonegap push plugin as old one is deprecated, and it keeps giving me an error in console: Uncaught ReferenceError: module is not defined --- Line 154 Push.js and i dont have much experience with cordova, so can anyone assist me ? Sep 12, 2015
@macdonst
Copy link
Member

@vikas091 how did you add the plugin to your project? Did you use the cordova/phonegap CLI?

@jokabuyasina
Copy link

i tried phonegap or cordova still getting the same Error: Plugin "PushPlugin" failed to install

@pOoOf
Copy link
Author

pOoOf commented Sep 17, 2015

@macdonst yes i added the plugin using cordova CLI and i dont know what caused this error but now everything seems to be working fine. Thanks

@pOoOf pOoOf closed this as completed Sep 17, 2015
@bobolat
Copy link

bobolat commented Mar 22, 2016

what is the solution on this?

@romuloinnocencio
Copy link

romuloinnocencio commented Jul 21, 2016

I got something like this....
*1 - I run: *

cordova plugin add phonegap-plugin-push --variable SENDER_ID="myNumberBlablabla";

*2 - set on config.html

<plugin name="phonegap-plugin-push" version="1.7.4" src="https://github.com/phonegap/phonegap-plugin-push.git" spec="1.7.4">
    <variable name="SENDER_ID" value="myNumberBlablabla" />
  </plugin>

* 3 - in index.html*

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/push.js"></script>

** 4 - I copy into www/scripts this script... **

/* global cordova:false */
/* globals window */

/*!
 * Module dependencies.
 */

var exec = cordova.require('cordova/exec');

/**
 * PushNotification constructor.
 *
 * @param {Object} options to initiate Push Notifications.
 * @return {PushNotification} instance that can be monitored and cancelled.
 */

var PushNotification = function(options) {
    this._handlers = {
        'registration': [],
        'notification': [],
        'error': []
    };

    // require options parameter
    if (typeof options === 'undefined') {
        throw new Error('The options argument is required.');
    }

    // store the options to this object instance
    this.options = options;

    // triggered on registration and notification
    var that = this;
    var success = function(result) {
        if (result && typeof result.registrationId !== 'undefined') {
            that.emit('registration', result);
        } else if (result && result.additionalData && typeof result.additionalData.actionCallback !== 'undefined') {
            var executeFunctionByName = function(functionName, context /*, args */) {
                var args = Array.prototype.slice.call(arguments, 2);
                var namespaces = functionName.split('.');
                var func = namespaces.pop();
                for (var i = 0; i < namespaces.length; i++) {
                    context = context[namespaces[i]];
                }
                return context[func].apply(context, args);
            };

            executeFunctionByName(result.additionalData.actionCallback, window, result);
        } else if (result) {
            that.emit('notification', result);
        }
    };

    // triggered on error
    var fail = function(msg) {
        var e = (typeof msg === 'string') ? new Error(msg) : msg;
        that.emit('error', e);
    };

    // wait at least one process tick to allow event subscriptions
    setTimeout(function() {
        exec(success, fail, 'PushNotification', 'init', [options]);
    }, 10);
};

/**
 * Unregister from push notifications
 */

PushNotification.prototype.unregister = function(successCallback, errorCallback, options) {
    if (!errorCallback) { errorCallback = function() {}; }

    if (typeof errorCallback !== 'function')  {
        console.log('PushNotification.unregister failure: failure parameter not a function');
        return;
    }

    if (typeof successCallback !== 'function') {
        console.log('PushNotification.unregister failure: success callback parameter must be a function');
        return;
    }

    var that = this;
    var cleanHandlersAndPassThrough = function() {
        if (!options) {
            that._handlers = {
                'registration': [],
                'notification': [],
                'error': []
            };
        }
        successCallback();
    };

    exec(cleanHandlersAndPassThrough, errorCallback, 'PushNotification', 'unregister', [options]);
};

/**
 * Call this to set the application icon badge
 */

PushNotification.prototype.setApplicationIconBadgeNumber = function(successCallback, errorCallback, badge) {
    if (!errorCallback) { errorCallback = function() {}; }

    if (typeof errorCallback !== 'function')  {
        console.log('PushNotification.setApplicationIconBadgeNumber failure: failure parameter not a function');
        return;
    }

    if (typeof successCallback !== 'function') {
        console.log('PushNotification.setApplicationIconBadgeNumber failure: success callback parameter must be a function');
        return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'setApplicationIconBadgeNumber', [{badge: badge}]);
};

/**
 * Get the application icon badge
 */

PushNotification.prototype.getApplicationIconBadgeNumber = function(successCallback, errorCallback) {
    if (!errorCallback) { errorCallback = function() {}; }

    if (typeof errorCallback !== 'function')  {
        console.log('PushNotification.getApplicationIconBadgeNumber failure: failure parameter not a function');
        return;
    }

    if (typeof successCallback !== 'function') {
        console.log('PushNotification.getApplicationIconBadgeNumber failure: success callback parameter must be a function');
        return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'getApplicationIconBadgeNumber', []);
};

/**
 * Get the application icon badge
 */

PushNotification.prototype.clearAllNotifications = function(successCallback, errorCallback) {
    if (!successCallback) { successCallback = function() {}; }
    if (!errorCallback) { errorCallback = function() {}; }

    if (typeof errorCallback !== 'function')  {
        console.log('PushNotification.clearAllNotifications failure: failure parameter not a function');
        return;
    }

    if (typeof successCallback !== 'function') {
        console.log('PushNotification.clearAllNotifications failure: success callback parameter must be a function');
        return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'clearAllNotifications', []);
};

/**
 * Listen for an event.
 *
 * The following events are supported:
 *
 *   - registration
 *   - notification
 *   - error
 *
 * @param {String} eventName to subscribe to.
 * @param {Function} callback triggered on the event.
 */

PushNotification.prototype.on = function(eventName, callback) {
    if (this._handlers.hasOwnProperty(eventName)) {
        this._handlers[eventName].push(callback);
    }
};

/**
 * Remove event listener.
 *
 * @param {String} eventName to match subscription.
 * @param {Function} handle function associated with event.
 */

PushNotification.prototype.off = function (eventName, handle) {
    if (this._handlers.hasOwnProperty(eventName)) {
        var handleIndex = this._handlers[eventName].indexOf(handle);
        if (handleIndex >= 0) {
            this._handlers[eventName].splice(handleIndex, 1);
        }
    }
};

/**
 * Emit an event.
 *
 * This is intended for internal use only.
 *
 * @param {String} eventName is the event to trigger.
 * @param {*} all arguments are passed to the event listeners.
 *
 * @return {Boolean} is true when the event is triggered otherwise false.
 */

PushNotification.prototype.emit = function() {
    var args = Array.prototype.slice.call(arguments);
    var eventName = args.shift();

    if (!this._handlers.hasOwnProperty(eventName)) {
        return false;
    }

    for (var i = 0, length = this._handlers[eventName].length; i < length; i++) {
        var callback = this._handlers[eventName][i];
        if (typeof callback === 'function') {
            callback.apply(undefined,args);
        } else {
            console.log('event handler: ' + eventName + ' must be a function');
        }
    }

    return true;
};

PushNotification.prototype.finish = function(successCallback, errorCallback, id) {
    if (!successCallback) { successCallback = function() {}; }
    if (!errorCallback) { errorCallback = function() {}; }
    if (!id) { id = 'handler'; }

    if (typeof successCallback !== 'function') {
        console.log('finish failure: success callback parameter must be a function');
        return;
    }

    if (typeof errorCallback !== 'function')  {
        console.log('finish failure: failure parameter not a function');
        return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'finish', [id]);
};

/*!
 * Push Notification Plugin.
 */

module.exports = {
    /**
     * Register for Push Notifications.
     *
     * This method will instantiate a new copy of the PushNotification object
     * and start the registration process.
     *
     * @param {Object} options
     * @return {PushNotification} instance
     */

    init: function(options) {
        return new PushNotification(options);
    },

    hasPermission: function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, 'PushNotification', 'hasPermission', []);
    },

    /**
     * PushNotification Object.
     *
     * Expose the PushNotification object for direct use
     * and testing. Typically, you should use the
     * .init helper method.
     */

    PushNotification: PushNotification
};

 var app = {
      // Application Constructor
      initialize: function() {
          this.bindEvents();
      },
      // Bind Event Listeners
      //
      // Bind any events that are required on startup. Common events are:
      // 'load', 'deviceready', 'offline', and 'online'.
      bindEvents: function() {
          document.addEventListener('deviceready', this.onDeviceReady, false);
      },
      // deviceready Event Handler
      //
      // The scope of 'this' is the event. In order to call the 'receivedEvent'
      // function, we must explicitly call 'app.receivedEvent(...);'
      onDeviceReady: function() {
          console.log('Received Device Ready Event');
          console.log('calling setup push');
          app.setupPush();
      },
      setupPush: function() {
          console.log('calling push init');
          var push = PushNotification.init({
              "android": {
                  "senderID": "582520927042"
              },
              "ios": {
                  "sound": true,
                  "vibration": true,
                  "badge": true
              },
              "windows": {}
          });
          console.log('after init');

          push.on('registration', function(data) {
              console.log('registration event: ' + data.registrationId);

              var oldRegId = localStorage.getItem('registrationId');
              if (oldRegId !== data.registrationId) {
                  // Save new registration ID
                  localStorage.setItem('registrationId', data.registrationId);
                  // Post registrationId to your app server as the value has changed
              }

              var parentElement = document.getElementById('registration');
              var listeningElement = parentElement.querySelector('.waiting');
              var receivedElement = parentElement.querySelector('.received');

              listeningElement.setAttribute('style', 'display:none;');
              receivedElement.setAttribute('style', 'display:block;');
          });

          push.on('error', function(e) {
              console.log("push error = " + e.message);
          });

          push.on('notification', function(data) {
              console.log('notification event');
              navigator.notification.alert(
                  data.message,         // message
                  null,                 // callback
                  data.title,           // title
                  'Ok'                  // buttonName
              );
         });
      }
  };

and i got this
push.js:247 Uncaught ReferenceError: module is not defined


##I'm using

  • Visual Studio 2015;
  • Cordova;
  • RequireJS;
  • and trying to run Debug -> Android -> VS Emulator 5' Kitkat (http://prntscr.com/bvso17);

@jcesarmobile
Copy link
Collaborator

In step 3 don't include push.js, just cordova.js if you don't have it already.

Skip the whole step 4

@romuloinnocencio
Copy link

romuloinnocencio commented Jul 21, 2016

If I run with Ripple, this project runs but i'm not sure if PushNotification is active or running;


if I change to the VS Emulator 5' Kitkat, returns a lot of erros;
http://prntscr.com/bvspdx

All SDK I'been downloaded
http://prntscr.com/bvsr1f

@romuloinnocencio
Copy link

Using Ripple, i see push.js have been loaded into my project =)
http://prntscr.com/bvsxkw

@macdonst
Copy link
Member

@romuloinnocencio Push won't work on Ripple. We are working on browser support.

@romuloinnocencio
Copy link

Hum, and how can test in VS Emulator 5' Kitkat or another.... it's my first app/contact with this kind of situation.

@macdonst
Copy link
Member

@romuloinnocencio You can't test push on an emulator or simulator. It just doesn't work.

@romuloinnocencio
Copy link

romuloinnocencio commented Jul 21, 2016

Right, and what can i do? How can i BUILD a app and transfer to my device and test, any advice?

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.google.android.gms:play-services-gcm:+.
     Searched in the following locations:
         https://repo1.maven.org/maven2/com/google/android/gms/play-services-gcm/maven-metadata.xml
         https://repo1.maven.org/maven2/com/google/android/gms/play-services-gcm/
         file:/usr/share/java/android-sdk-macosx/extras/android/m2repository/com/google/android/gms/play-services-gcm/maven-metadata.xml
         file:/usr/share/java/android-sdk-macosx/extras/android/m2repository/com/google/android/gms/play-services-gcm/
     Required by:
         :android:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

I delete and reinstall ( http://prntscr.com/bvtn1y )

@lock
Copy link

lock bot commented Jun 4, 2018

This thread has been automatically locked.

@lock lock bot locked as resolved and limited conversation to collaborators Jun 4, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

6 participants