chrome.gcm

2014-10-24T00:00:00+00:00 Chrome Extension JavaScript Java

参考1: https://developer.chrome.com/apps/cloudMessaging

参考2: http://docs.monaca.mobi/3.5/ja/manual/backend/push_config/gcm/ (※主に設定の有効の仕方等)

ちょっと前にはchrome.pushMessagingっていうAPIが公開(って言っても一年以上前)されてたはずなのですが、現在これがどうもlegacy扱いになっている模様で現在はchrome.gcmを使うのが良いっぽそう。確かpushMessagingの方はwebstoreを経由してインストールしたアプリで無いと使えないのかどうかまでは覚えてないが、gcmはcrxパッケージングした拡張であれば使う事が可能らしい

っていう事でやってみた

※おそらくはChrome Sync(ChromeでのGoogleアカウントのログイン機能)をやっておかないと出来ないのかも知れない

APIへのアクセス権の設定

https://console.developers.google.com/project にアクセスして使用するプロジェクトを選択後「APIs & auth」のセクションからCredentialsを選択。Public API AccessからAPI KEYを取得(Server Key)

んでAPIsセクションにアクセスしてGoogle Cloud Messaging for ChromeをONにしておく

で作成したAPI KeyとプロジェクトのSender IDのProject Numberを控えておく manifest.json

{
  "name": "test",
  "version": "1.0",
  "manifest_version": 2,
  "background": {
    "scripts": ["bg.js"]
  },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": ["gcm"]
}

bg.js

chrome.browserAction.onClicked.addListener(function() {
  chrome.windows.create({ url: "popup.html" });
});

popup.html

<!DOCTYPE html>
<html>
  <body>
    <div id="messages"></div>
    <script src="popup.js"></script>
  </body>
</html>

popup.js

chrome.gcm.register(['上記で取得したProject Numberを指定'], function(regId) {
  // chrome.runtime.lastErrorを要チェック

  // サーバー等からこのクライアント側にプッシュ送信する際にはこのregIdの値が必要になる
  console.log('id: ' + regId);

  chrome.gcm.onMessage.addListener(function(res) {
    var message  = document.createElement('div');
    message.innerText = res.data.message;

    var messages = document.getElementById('messages');
    messages.appendChild(message);
  });
});

まぁここまでが拡張機能の実装なので、ここまでやったら拡張をcrxにビルドしてインストール。その後ブラウザアクションが追加されてるはずなのでクリックしてコンソールを開くとregIdの値が出力されているはずなのでそれも控えておく curlでプッシュ送信

#!/bin/sh

curl \
    -H "Content-Type:application/x-www-form-urlencoded" \
    -H "Authorization: key=上記で取得したAPI KEYを指定" \
    -d "registration_id=拡張ウィンドウ側のコンソールに出力されたregIdを指定" \
    -d data.message='データ' \
    https://android.googleapis.com/gcm/send

てな感じでchrome.gcmで取得したregIdを使ってChrome側にプッシュ送信出来る模様 Java(HttpsURLConnection)でプッシュ送信

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class Main {

    private static final String GCM_URL = "https://android.googleapis.com/gcm/send";
    private static final String API_KEY = "API KEY";
    private static final String REG_ID  = "取得したregIdを指定";

    public static void main(String[] args) {
        try {
            HttpsURLConnection conn = (HttpsURLConnection)new URL(GCM_URL).openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Authorization", "key=" + API_KEY);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.write(("registration_id=" + REG_ID + "&data.message=hoge").getBytes());

            conn.connect();

            try (InputStream is = conn.getInputStream()) {
                byte[] b = new byte[4096];

                while (is.read(b) != -1) {
                    System.out.println(new String(b));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

終わり。詳しい事はサーバー側等からリクエストを送る際にGoogle Cloud Messaging for AndroidがONになってないとHTTP/401 Unauthorize failureする事がある

んまx一応プッシュ送信する仕組みが良い感じに使えるようになったのでは(以前と比べると)

Javaで同時リクエストをテストする方法 JAX-RSをやってみる (20) - SecurityEntityFiltering -