Search code examples
javascripthtmlclientmqtt

mqtt client in html page


I want to have a web page that can publish and subscribe to a mqtt broker. I also want communicate to the broker using the 1883 port - not a websoctets.

is this possible - does anyone have any working examples .. I'm a real novice , and admit i dont fully understand the difference between nodejs and javascript.

I have a html page made up , it has a checkbox setup, the checkbox is set to switch an led on an esp8266 through a mqtt broker. after i load the page - the switch works... but i'd like as soon as i load the web page that it would chek the status of the led and reflect that on the check box. ie: when I load the page I can see if the led is on or off.

I have a working nodejs script that can publish a request for a status to the led, and subscribes for the repsonce .. and it sucessfully recieves a responce..

is there any way i can build this script into my html page such that when it loads -it gets the responce from the script and sets the checkbox accordinaly ?

I see some examples of java mqtt html clients but these seem to only work with websockets. In my project I'm not sure what listner ports I am allowed to use for the websockets ( if any) so would prefer to stick with mqtt port 1883.

all thoughts welcome please ? thanks


Solution

  • If you want to connect to a MQTT broker from with a web page you MUST use MQTT over Websockets. The Javascript sandbox in the browser will not allow you to do it any other way.

    You will need to use a MQTT broker that supports MQTT over Websockets and you will most likely need to configure it to do so. It will need to be on a separate port to 1883 as this is traditionally used for native MQTT.

    You can use either the Paho JavaScript library (https://www.eclipse.org/paho/index.php?page=clients/js/index.php) or the MQTT.js library (https://www.npmjs.com/package/mqtt) in the browser. Both libraries come with examples.

    We will not just provide examples here on Stack Overflow, try with examples supplied by the libraries and if you get stuck, open a new question and show what you tried and explain what is not working and we will help you fix it.