Make a new HTML file. Save this code as index.html in your folder.
<!DOCTYPE html>
<html>
<head>
<title>Publish Subscribe Tutorial</title>
</head>
<body>
<input id="publish-button" type="submit" value="PubNub Publish..."/>
</body>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.21.7.min.js"></script>
<script>
const pubnub = new PubNub({
publishKey : 'YOUR PUBNUB PUBLISH KEY HERE',
subscribeKey : 'YOUR PUBNUB SUBSCRIBE KEY HERE'
});
const button = document.getElementById('publish-button');
button.addEventListener('click', () => {
pubnub.publish({
channel : 'pubnub_onboarding_channel',
message: 'Hellloo From JavaScript SDK'
}, function(status, response) {
// Handle error here
});
});
pubnub.subscribe({
channels: ['pubnub_onboarding_channel']
});
pubnub.addListener({
message: function(event) {
let pElement = document.createElement('p');
pElement.appendChild(document.createTextNode(event.message));
document.body.appendChild(pElement);
}
});
</script>
</html>
This page is subscribed. Open index.html in your web browser and click the button. You'll see the publish here - in real time.
[Subscribed Log Area Here]