LoginSignup
13

More than 5 years have passed since last update.

JSを使ってプッシュ通知を配信してみる

Posted at

ニフティクラウドmobile backendのJSSDKver2.0を活用してプッシュ通知を送ってみた。

というのもこちらの記事で書かれていたものがSDKのver2.0から利用できなくなったので更新した。

コードはこんな感じ

HTMLはこんな形

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>プッシュ!</title>
    <link href="//code.htmlhifive.com/h5.css" rel="Latest">
    <!-- stylesheet compiled and minified CSS -->
    <link rel="stylesheet" href="bootstrap.min.css">
    <link href="style.css" rel="stylesheet">
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  </head>
  <body>
    <div class="container">
      <div class="row marketing">
        <div class="col-lg-12">
      <form role="form">
        <div class="form-group">
          <label for="exampleInputEmail1">メッセージ</label>
          <input type="text" class="form-control" id="message" placeholder="メッセージを入力してください">
        </div>
        <button type="submit" class="btn btn-default submit-button">プッシュ!</button>
      </form>
        </div>
      </div>
      <div class="message">
      </div>
    </div> <!-- /container -->
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="jquery.min.js"></script>
    <script src="bootstrap.min.js"></script>
    <script src="ncmb.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

jsはこんな感じ

api.js
$(
  function() {
  var client_key = window.prompt("クライアントキーを入力してください", "");
  if (client_key == '') {
    alert("クライアントキーが入力されていませんので利用できません");
    return false;
  }
  //ニフティクラウド mobile backendを初期化しています
  var ncmb = new NCMB("APP_KEY", client_key);

  // フォームの送信時のイベントを取得しています
  $("form").on("submit", function(e) {
    var message;
    e.preventDefault();
    message = $("#message").val();

    // ここからがプッシュ作成処理になります

    var push = new ncmb.Push();
    push.set("immediateDeliveryFlag", true)
        .set("message", "Hello, World!")
        .set("target", ["android"])
        .set("searchCondition", {"deviceToken":"Your_deviceToken"});

    push.send()
        .then(function(push){
          // 送信後処理
          })
        .catch(function(err){
          // エラー処理
     });


   });
});

今回はWeb画面でやったけど、ラズパイとかでも応用できるので次回はラズパイでやってみよう!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13