На прошлой неделе я интегрировал firebase в свой проект, и мне это очень нравится, поэтому сегодня я сделаю простое приложение, чтобы познакомить вас с firebase — возможно, оно вам тоже понравится.

Логика

Всякий раз, когда пользователь посещает наш веб-сайт, мы создаем соединение с firebase. И затем мы можем отправить уведомление пользователю, когда захотим. Конечно, пользователь покинул наш сайт раньше, этого не видно.

Воплощать в жизнь

Во-первых, нам нужно создать новый проект. После этого мы получаем ключ API и кучу вещей, как показано ниже.

Затем мы создаем html-файл, который играет роль для подключения пользователя к нашему проекту firebase. Это всего лишь простой html-файл, у меня есть команда из важной части, чтобы вы могли легко ее понять.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="description" content="Using firebase to implement realtime notification">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Realtime Notification</title>

  <!-- Disable tap highlight on IE -->
  <meta name="msapplication-tap-highlight" content="no">

  <!-- Web Application Manifest -->
  <link rel="manifest" href="manifest.json">

  <!-- Add to homescreen for Chrome on Android -->
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="Realtime Notification">
  <meta name="theme-color" content="#303F9F">

  <!-- Add to homescreen for Safari on iOS -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="Realtime Notification">
  <meta name="apple-mobile-web-app-status-bar-style" content="#303F9F">

  <!-- Tile icon for Win8 -->
  <meta name="msapplication-TileColor" content="#3372DF">
  <meta name="msapplication-navbutton-color" content="#303F9F">

  <!-- App Styling -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en">
</head>
<body>
<div style="text-align:center;">
  <h1>Push notification</h1>
  <form id="message-form" action="#">
    <input type="text" name="message" id="message">
    <button id="submit" disabled type="submit">
      Send
    </button>
  </form>
</div>

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.3.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyBVqfmstwgSRmzRpHYW87EF8J7JTUB8UXU",
    authDomain: "realtime-push-notificati-2a832.firebaseapp.com",
    databaseURL: "https://realtime-push-notificati-2a832.firebaseio.com",
    storageBucket: "realtime-push-notificati-2a832.appspot.com",
  };
  firebase.initializeApp(config);
</script>
<script src="scripts/main.js"></script>
</body>
</html>

Далее мы создадим класс, который будет обрабатывать соединение с firebase.

'use strict';

function RealtimeNotification() {

  firebase.auth().signInAnonymously().catch(function (error) {
    // Handle Errors here.
    var errorCode = error.code
    var errorMessage = error.message
    console.log(errorCode, errorMessage)
  })

  this.database = firebase.database()
}

window.onload = function() {
  window.RealtimeNotification = new RealtimeNotification()
};

В этом уроке мы будем использовать аноним, вы должны включить его на консоли Firebase.

Далее мы будем прослушивать базу данных firebase, всякий раз, когда в базе данных будут новые записи, мы покажем их пользователю. Обновите наш класс, как показано ниже.

function RealtimeNotification() {

  firebase.auth().signInAnonymously().catch(function (error) {
    // Handle Errors here.
    var errorCode = error.code
    var errorMessage = error.message
    console.log(errorCode, errorMessage)
  })

  this.database = firebase.database()
  this.newItems = false

  this.loadMessages()
}

// Listen to the change of firebase database
RealtimeNotification.prototype.loadMessages = function() {
  this.messagesRef = this.database.ref('messages')
  this.messagesRef.off()

  let setMessage = function (data) {
    if (!this.newItems) return
    let message = data.val()
    alert(message.text)
  }.bind(this)

  this.messagesRef.on('child_added', setMessage)
  this.messagesRef.on('value', function(messages) {
    this.newItems = true
  }.bind(this))
};

Вы заметите, что я добавил в код флаг newItems. Это поможет мне просто отобразить новое сообщение, поскольку база данных firebase также получает старое сообщение.

Наше приложение почти готово, но мы не можем отправить уведомление для тестирования, поэтому я поместил текстовое поле в html-файл, чтобы помочь мне в этом. Потому что я добавил его сверху, поэтому я буду использовать его сейчас.

Создайте функцию для обработки событий, когда пользователь взаимодействует с нашим текстовым полем и кнопкой отправки, добавив строки в функцию RealtimeNotification.

this.messageForm = document.getElementById('message-form')
  this.messageInput = document.getElementById('message')
  this.submitButton = document.getElementById('submit')
  this.messageForm.addEventListener('submit', this.saveMessage.bind(this))

Далее мы рассмотрим функцию, помогающую пользователю сохранять данные в базу данных firebase. Поскольку наша база данных firebase является базой данных в реальном времени, поэтому другой пользователь получит обновление и увидит наше сообщение.

// Push notification to firebase database
RealtimeNotification.prototype.saveMessage = function(e) {
  e.preventDefault()
  if (this.messageInput.value) {
    this.messagesRef.push({
      text: this.messageInput.value,
    }).then(function() {
      this.messageInput.value = ''
      this.toggleButton()
    }.bind(this)).catch(function(error) {
      console.error('Error writing new message to Firebase Database', error)
    })
  }
};

Наконец, мы создаем некоторые функции для проверки ввода пользователя. И мы получили готовый файл вот так.

'use strict';

function RealtimeNotification() {
  this.checkSetup()

  firebase.auth().signInAnonymously().catch(function (error) {
    // Handle Errors here.
    var errorCode = error.code
    var errorMessage = error.message
    console.log(errorCode, errorMessage)
  })

  this.database = firebase.database()
  this.newItems = false

  this.messageForm = document.getElementById('message-form')
  this.messageInput = document.getElementById('message')
  this.submitButton = document.getElementById('submit')
  this.messageForm.addEventListener('submit', this.saveMessage.bind(this))

  var buttonTogglingHandler = this.toggleButton.bind(this)
  this.messageInput.addEventListener('keyup', buttonTogglingHandler)
  this.messageInput.addEventListener('change', buttonTogglingHandler)

  this.loadMessages()
}

// Listen to the change of firebase database
RealtimeNotification.prototype.loadMessages = function() {
  this.messagesRef = this.database.ref('messages')
  this.messagesRef.off()

  let setMessage = function (data) {
    if (!this.newItems) return
    let message = data.val()
    alert(message.text)
  }.bind(this)

  this.messagesRef.on('child_added', setMessage)
  this.messagesRef.on('value', function(messages) {
    this.newItems = true
  }.bind(this))
};

// Push notification to firebase database
RealtimeNotification.prototype.saveMessage = function(e) {
  e.preventDefault()
  if (this.messageInput.value) {
    this.messagesRef.push({
      text: this.messageInput.value,
    }).then(function() {
      this.messageInput.value = ''
      this.toggleButton()
    }.bind(this)).catch(function(error) {
      console.error('Error writing new message to Firebase Database', error)
    })
  }
};

// Only enable submit button whenever input field not empty
RealtimeNotification.prototype.toggleButton = function() {
  if (this.messageInput.value) {
    this.submitButton.removeAttribute('disabled')
  } else {
    this.submitButton.setAttribute('disabled', 'true')
  }
};

// Checks that the Firebase SDK has been correctly setup and configured.
RealtimeNotification.prototype.checkSetup = function() {
  if (!window.firebase || !(firebase.app instanceof Function) || !window.config) {
    window.alert('You have not configured and imported the Firebase SDK. ' +
        'Make sure you go through the codelab setup instructions.')
  } else if (config.storageBucket === '') {
    window.alert('Your Firebase Storage bucket has not been enabled. Sorry about that. This is ' +
        'actually a Firebase bug that occurs rarely. ' +
        'Please go and re-generate the Firebase initialisation snippet (step 4 of the codelab) ' +
        'and make sure the storageBucket attribute is not empty. ' +
        'You may also need to visit the Storage tab and paste the name of your bucket which is ' +
        'displayed there.')
  }
};

window.onload = function() {
  window.RealtimeNotification = new RealtimeNotification()
};

Вы можете проверить, введя сообщение и нажав кнопку отправки, оно доставит наше сообщение всем другим пользователям, которые также посещают наше веб-приложение. Я развернул код, и вы можете легко протестировать его здесь:



И репозиторий на гитхабе:



Спасибо за чтение, надеюсь, вы, ребята, сможете сделать несколько интересных приложений с помощью firebase.