Web browsers use the http protocol and modern ones can also use websockets.
To publish and subscribe to an MQTT broker with a browser you will need to use JavaSript MQTT over websockets client.
Details of both methods including download links are here.
The first thing you will need to do is create a basic web page. An outline structure is shown below:
We will now create a simple script that connects to a broker and publishes a message.
A screen shot of the script is show below:
Note: scripts used in this tutorial can be downloaded here.
Running the script
To run the script copy it into a file called websocks.htm and double click to run it.
When you load the page at the bottom of the page a call to MQTTconnect is made. (see code above)
The MQTTconnect sets up the connection and importantly sets the onsuccess callback.
The onConnect function is called when the connection is successful.
Note: you can assign an on fail function as well but I haven’t done so to keep it short.
You can only subscribe and publish when the connection is established which is why many scripts will subscribe and publish in the onConnect function.
I have commented out the subscribe call in the above script.
To view messages you will need to enable console logging on Firefox click tools>web developer>web console.
Not much happens when you run the script and you will need to console log screen to see the output. Which I’ve shown below:
If you are running your own local broker then you will see the connection and publish from the client as shown above:
- Don’t use document.write anywhere in the script! Always use console.log to see messages.
Publishing, Subscribing and Receiving Messages
Now we will modify the script to:
- Subscribe to a topic
- Process any received messages.
- Handle connection failures
First we modify the connect function to add callbacks for failure and message received. the modified function is shown below:
Now we create the two functions. The onFailure function shown below logs a message and attempts a reconnect every few seconds set by the reconnecttimeout variable.:
The onMessageArrived function extracts the message and topic and logs them
Now we uncomment the subscribe call in the onConnect function to complete the changes..
Now if we run the script and simulate a failure by using the wrong port number we get the result below:
Now we run the script using the correct port and we get our published message logged to the console
- HiveMQ using the Javacript client.