
Ми всі знайомі з миттєвими повідомленнями та використовуємо їх для спілкування з людьми в режимі реального часу. Однак іноді нам може знадобитися програма, яка дозволяє нам анонімно надсилати повідомлення друзям або анонімно спілкуватися з незнайомцями в безпосередній близькості. Прикладом такого додатка є "Правда", який дозволяє спілкуватися з людьми у вашому списку контактів, не розкриваючи вашу особу.
У цьому підручнику я покажу вам, як створити загальнодоступний анонімний додаток для чату в JavaScript (використовуючи NodeJS і Express на сервері, і VanillaJS на клієнті) та Pusher. Pusher дозволяє нам створювати масштабовані та надійні програми реального часу. Оскільки нам потрібна доставка повідомлень чату в режимі реального часу, це ключовий компонент програми чату. На зображенні нижче зображено те, що ми будуватимемо:

Починаємо
Давайте почнемо, зареєструвавшись у безкоштовному обліковому записі Pusher (або увійшовши, якщо у вас він вже є). Увійшовши в систему, створіть на приладовій панелі нову програму Pusher та занотуйте свій ідентифікатор програми, ключ та секрет, які є унікальними для програми.
Щоб створити нову програму Pusher, натисніть Your apps
бічне меню, а потім -Create a new app
під шухлядою. Це відкриє майстер налаштування.
- Введіть назву програми. У цьому випадку я називатиму це "чатом".
- Виберіть кластер.
- Виберіть опцію «Створити програму для кількох середовищ», якщо ви хочете мати різні екземпляри для розробки, постановки та виробництва.
- Виберіть Vanilla JS як інтерфейс і NodeJS як серверну.
- Завершіть процес, натиснувши
Create my app
кнопку, щоб налаштувати екземпляр програми.

Кодування сервера
We need a backend which will serve our static files and also accept messages from a client and then broadcast to other connected clients through Pusher. Our backend will be written in NodeJS, so we need to set it up.
We need a package.json
file, and I’ll add it by running the command below. I’ll use the defaults provided by hitting enter for every prompt.
With the package.json
file added, I’ll install Express, body-parser, and Pusher npm packages. Run the following command:
With these packages installed, let’s add a new file called server.js
with the following content:
var express = require('express');var bodyParser = require('body-parser');var Pusher = require('pusher');
var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));
var pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER" });
app.post('/message', function(req, res) { var message = req.body.message; pusher.trigger( 'public-chat', 'message-added', { message }); res.sendStatus(200);});
app.get('/',function(req,res){ res.sendFile('/public/index.html', {root: __dirname });});
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 5000;app.listen(port, function () { console.log(`app listening on port ${port}!`)});
With the code above, we have defined an end-point /message
which will be used by one client to send a message to another through Pusher. The other routes are used to serve the static files which we will add later.
Replace the placeholder strings App ID, Secret, and Key with the values from your Pusher dashboard. Add this statement "start": "node server.js"
in the script property of our package.json
file. This will allow us to start the server when we run npm start.
Building the frontend
Moving on to the frontend, let’s add a new folder called public. This folder will contain our page and JavaScript files. Add a new file called style.css with the content below, which will hold our style definition for the page.
@import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");.chat{ list-style: none; margin: 0; padding: 0;}
.chat li{ margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px dotted #B3A9A9;}
.chat li.left .chat-body{ margin-left: 60px;}
.chat li.right .chat-body{ margin-right: 60px;}
.chat li .chat-body p{ margin: 0; color: #777777;}
.panel .slidedown .glyphicon, .chat .glyphicon{ margin-right: 5px;}
.body-panel{ overflow-y: scroll; height: 250px;}
::-webkit-scrollbar-track{ -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); background-color: #F5F5F5;}
::-webkit-scrollbar{ width: 12px; background-color: #F5F5F5;}
::-webkit-scrollbar-thumb{ -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); background-color: #555;}
Add another file called index.html with the markup below.

Original text
Anonymous Chat - Refresh
- Available
- Busy
- Away
- Sign Out
Send

{{body}}
{{body}}
I’m using a template from bootsnipp which has been slightly modified to display just the name and message.
Add a new file called index.js with the content below. Remember to add the Pusher app details:
$(document).ready(function(){ var pusher = new Pusher('APP_KEY', { cluster: 'APP_CLUSTER', encrypted: false });
let channel = pusher.subscribe('public-chat'); channel.bind('message-added', onMessageAdded);
$('#btn-chat').click(function(){ const message = $("#message").val(); $("#message").val("");
//send message $.post( "//localhost:5000/message", { message } ); });
function onMessageAdded(data) { let template = $("#new-message").html(); template = template.replace("{{body}}", data.message);
$(".chat").append(template); }});
With the code in this file, we get the message to be sent and then call the server with the message. After that, we connect to Pusher by creating a new Pusher object with the App Key and the Cluster that you set earlier.
We subscribe to a channel and an event named message-added
. The channel is a public channel so it can be named any way you like. I’ve chosen to prefix mine with public-
but that’s just my own personal naming convention as there are no rules for a public channel. The difference between a public
channel and a private
or presence
channel is that a public channel does not require a client to be authenticated and can be subscribed to by anyone that knows the name of the channel. You can read more about Pusher channels here.
We bind to the click event of the chat button on the page, retrieve the message from the textbox on the page, and then send it to the server with the username. With all we have setup, we can start the app by running npm start
. Here’s a glimpse of how it works on my computer.

Wrap Up
This is a app to show how you can use Pusher to send messages in real-time. We built a public anonymous chat app that allows your website visitors to send anonymous messages to each other in real-time. You can find the code here on GitHub
This was originally published on Pusher