已废弃 Gecko 51 (Firefox 51 / Thunderbird 51 / SeaMonkey 2.48)
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

非标准
该特性是非标准的,请尽量不要在生产环境中使用它!

Note: The proprietary Simple Push API is deprecated in favor of the W3C Push API.

简单推送A​​PI,也称为推送通知API,提供应用程式唤醒以接收通知的功能。您可以使用简单推送作为一个同步机制,甚至可以从第三方服务器获取最新数据。

推送就是从远程服务端发来的一个事件.他的工作原理如下: An app uses the Simple Push API to request a special, unique URL called an endpoint. This request goes to an existing server maintained by Mozilla for this purpose (this is called the "push server"). When the app receives the endpoint back from the push server, the app sends the endpoint to its own server (your app server). The app server stores this endpoint, then when it wants to wake up the app, it calls the endpoint with a version number, and the push server contacts the app with a notification of the version number. The app can be made to do something when it receives the notification, including ignoring it.

The Simple Push API extends Window.navigator with a push property which is a PushManager object, and adds some new events you can receive to monitor the push status.

基础示例

There are several ways to use the Simple Push API. This example covers the basics of how to use it. The example consists of the general steps below. See the following sections for full information on each step.

  1. Add push configuration to the app's manifest file
  2. Call PushManager.register to request an endpoint
  3. Send the endpoint to your server
  4. Add message handlers for push notifications to your app
  5. Send a notification from your server using the endpoint

1. Add push configuration to the app's manifest file

You need to change two things in the app's manifest file so it can use Simple Push:

  1. messages field - Add push and push-register to messages.
    These indicate the app page that will receive each of these events (push and push-register). In this example, both are going to the same page: "/index.html", but they can use other pages also. See below for a more information on each of these events.
  2. permissions field - Add that your app wants to receive push notifications.
    It's a good idea to provide a clear description here so that the end user will understand why you need push permissions.
"messages": [
   { "push": "/index.html"},
   { "push-register": "/index.html"}
],
"permissions": {
  "push": {
    "description": "Required for being updated with new goals in soccer matches"
  }
}

2. Call PushManager.register() to request an endpoint

The app needs to request an endpoint by calling PushManager.register. You have to decide when this should be called. You could call it when the user has logged in to your service, or when the user decides to start watching a soccer match, or at some other point. The code below is one way to do it.

if (navigator.push) {
  // Request the endpoint. This uses PushManager.register().
  var req = navigator.push.register();
  req.onsuccess = function(e) {
    var endpoint = req.result;
      console.log("New endpoint: " + endpoint );
      // At this point, you'd use some call to send the endpoint to your server.
      // For instance:
      /*
      var post = XMLHTTPRequest();
      post.open("POST", "https://your.server.here/registerEndpoint");
      post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      post.send("endpoint=" + encodeURIComponents( endpoint ) );
      */
      // Obviously, you'll want to add .onload and .onerror handlers, add user id info,
      // and whatever else you might need to associate the endpoint with the user.
    }
   req.onerror = function(e) {
     console.error("Error getting a new endpoint: " + JSON.stringify(e));
   }
} else {
  // push is not available on the DOM, so do something else.
}

3. Send the endpoint to your server

Once the app has received an endpoint, it needs to send it to your app server. There is more than one way to do this. For example you can send it by email, or send it by POST, PUT, or even GET. We recommend that you store the endpoint with some user data from the app, such as a cookie, a username, or whatever you use to identify your endpoint-user pair.

But if you are sending to your server, we recommend that you follow these good practices:

  • Send it by XMLHttpRequest.
  • Always use HTTPS. Otherwise if someone intercepts your endpoint, they could start sending notifications to your app.
  • Use something to match the user (or app installation) to the endpoint, like a cookie.
  • Keep the endpoint safe! Anyone with your endpoint could cause your app to drain your customer's battery or needlessly tie up your server, or other annoyances. You can always have the client fetch a new endpoint and drop the old one, but be aware that you'll want to make sure your server acknowledges the change.

4. Add message handlers for push notifications to your app

Once you have set up your endpoint as in the steps above, you are ready to have the app start listening for push and push-register messages using message handlers. 

Add a push message handler

The push message handler could be in your index.html file or in your main.js script, or even in a specific push-message.html file that contains only the message handler. That could be useful if a push message is sent and your app is closed, because it will load just a small part of the HTML/JavaScript code, and you can decide if the app needs to be fully open or do something in the background. Wherever you decide to place the push message handler, make sure that the manifest file points to the right location (see the first step above), otherwise your app may not get updates. Here is an example of a push message handler:

if (window.navigator.mozSetMessageHandler) {
  window.navigator.mozSetMessageHandler('push', function(e) {
    console.log('My endpoint is ' + e.pushEndpoint);
    console.log('My new version is ' +  e.version);
    //Remember that you can handle here if you have more than
    //one pushEndpoint
    if (e.pushEndpoint === emailEndpoint) {
      emailHandler(e.version);
    } else if (e.pushEndpoint === imEndpoint) {
      imHandler(e.version);
    }
  });
} else {
  // No message handler
}

Add a push-register message handler

Note: Be sure to add this handler and check that it works. If you do not re-register your endpoints when this message is received by your app, the app WILL NOT BE ABLE to receive further push notifications.

A push-register message will be sent to all apps when the device changes its internal identifier (called the UAID or User Agent Identifier). This could be because the push server has changed, or it has gone down and needs to recover, or other circumstances. If one of these things occurs, you MUST re-register all your endpoints, because your previous endpoints will not be valid anymore. Therefore your app needs to implement a push-register message handler. See the example code below.

if (window.navigator.mozSetMessageHandler) {
  window.navigator.mozSetMessageHandler('push-register', function(e) {
    console.log('push-register received, I need to register my endpoint(s) again!');
    var req = navigator.push.register();
    req.onsuccess = function(e) {
      var endpoint = req.result;
      console.log("New endpoint: " + endpoint );
      localStorage.endpoint = endpoint;
    }
    req.onerror = function(e) {
      console.error("Error getting a new endpoint: " + JSON.stringify(e));
    }
  });
} else {
  // No message handler
}

5. Send a notification from your server using the endpoint

Once you have the endpoint on your server, you can send a notification by simply sending an HTTP PUT request to the endpoint with the body version=<version>. For example, imagine an endpoint with this URL:

https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef

and version 5:

version=5

Here is how the notification looks using curl:

curl -X PUT -d "version=5" https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef

If the push server is running correctly, you will get a response with a 200 Status (OK) and a {} as a body. You may also receive a 202 Status, indicating that the message was accepted, but may be handled using an alternate system. If not, a valid HTTP error response with JSON explaining the error is returned.

Please remember: Just because Simple Push has accepted the message, there is no guarantee that the message will be delivered successfully to the app. Many factors, ranging from a device being offline to various network failures, may prevent successful delivery of a notification. We try our best, but sometimes the universe has other plans.

Remember that the value of version should be integer numbers, and incremental. Apps will not get new notifications if the new version is lower than that stored on the server and/or device. Versions can be useful to the app to indicate if there are "missed" events it should really check up on. You could also just use the current UTC (the number of seconds since midnight, Jan. 1, 1970, GMT) if the actual version value isn't very important to you.

Unregister an endpoint

Once you finish using an endpoint and you do not want to receive more notifications, we kindly ask you to unregister the old endpoint using PushManager.unregister. This will clean up the amount of data the device sends to the push server, and will also will lower the battery usage by not sending notifications for apps that will not use them.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 未实现 未实现 未实现 未实现 未实现
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 未实现 未实现 未实现 未实现 未实现

See also

文档标签和贡献者