Search code examples
javascriptgoogle-chromegoogle-chrome-extensiongoogle-cloud-messagingchrome-gcm

How to obtain registration token from GCM connection servers for Chrome app?


I'm working on a chrome app/extension that receives push notification using Google Cloud Messaging API. And the tutorial that I'm following is this. Everything is clear until the "Obtain GCM Registration Token" part.

The code below explains a part of the registration process.

function registerCallback(registrationId) {
  if (chrome.runtime.lastError) {
    // When the registration fails, handle the error and retry the
    // registration later.
    return;
  }

  // Send the registration token to your application server.
  sendRegistrationId(function(succeed) {
    // Once the registration token is received by your server,
    // set the flag such that register will not be invoked
    // next time when the app starts up.
    if (succeed)
      chrome.storage.local.set({registered: true});
  });
}

function sendRegistrationId(callback) {
  // Send the registration token to your application server
  // in a secure way.
}

chrome.runtime.onStartup.addListener(function() {
  chrome.storage.local.get("registered", function(result) {
    // If already registered, bail out.
    if (result["registered"])
      return;

    // Up to 100 senders are allowed.
    var senderIds = ["Your-Sender-ID"];
    chrome.gcm.register(senderIds, registerCallback);
  });
});

I understand that we have to use chrome.gcm.register to register our app, but they haven't mentioned how the token will be obtained. Will the chrome.gcm.register method return something which can be used as the registration token? Help me with this please!

P.S: The tutorials that are available are pretty outdated. If anyone has any updated tutorials/samples, do tell me.


Solution

  • Your callback:

    function registerCallback(registrationId) {
    

    will get called and the registrationId passed to it. There you can save it to local storage or do whatever you want.