Skip to content

Instantly share code, notes, and snippets.

@ajb413
Created January 24, 2019 00:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajb413/b87f428f2eaaa76395d3a260f19650a2 to your computer and use it in GitHub Desktop.
Save ajb413/b87f428f2eaaa76395d3a260f19650a2 to your computer and use it in GitHub Desktop.

JavaScript

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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment