Browser

This example shows you how to connect a website to shiftr.io.

Please read first the Javascript Manual that explains the basics.

Code

Create a index.html file with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
    <script src="https://assets.shiftr.io/js/mqtt-2.9.0.js"></script>
    <script src="script.js" charset="utf-8"></script>
  </head>
  <body>
    <button id="button">Click Me</button>
  </body>
</html>

Create a script.js file with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// run this function when the document has loaded
$(function(){
  var client = mqtt.connect('wss://try:try@broker.shiftr.io', {
    clientId: 'javascript'
  });

  client.on('connect', function(){
    console.log('client has connected!');
  });

  client.on('message', function(topic, message) {
    console.log('new message:', topic, message.toString());
  });

  $('#button').click(function(){
    client.publish('/hello', 'world');
  })
})