Basic javascript example using Mosquitto MQTT

I am trying to get a basic example to work and it is not connecting to the MQTT broker. I double checked the host and port variables and they are correct, then I tested the broker and it is functioning correctly. Is there an error in the javascript?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">

    <title>Websockets Using JavaScript MQTT Client</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script src="" type="text/javascript"></script>
 	<script type = "text/javascript"
         src = ""></script>
    <script type = "text/javascript">

	function onConnectionLost(){
	console.log("connection lost");
	document.getElementById("status").innerHTML = "Connection Lost";
	document.getElementById("messages").innerHTML ="Connection Lost";
	function onFailure(message) {
		document.getElementById("messages").innerHTML = "Connection Failed- Retrying";
        setTimeout(MQTTconnect, reconnectTimeout);
		function onMessageArrived(r_message){
		out_msg="Message received "+r_message.payloadString+"<br>";
		out_msg=out_msg+"Message received Topic "+r_message.destinationName;
		//console.log("Message received ",r_message.payloadString);
		document.getElementById("messages").innerHTML =out_msg;
	function onConnected(recon,url){
	console.log(" in onConnected " +reconn);
	function onConnect() {
	  // Once a connection has been made, make a subscription and send a message.
	document.getElementById("messages").innerHTML ="Connected to "+host +"on port "+port;
	document.getElementById("status").innerHTML = "Connected";
	console.log("on Connect "+connected_flag);
	//message = new Paho.MQTT.Message("Hello World");
	//message.destinationName = "sensor1";

    function MQTTconnect() {
	document.getElementById("messages").innerHTML ="";
	var s = document.forms["connform"]["server"].value;
	var p = document.forms["connform"]["port"].value;
	if (p!="")
		console.log("port" +port);
	if (s!="")

	console.log("connecting to "+ host +" "+ port);
	mqtt = new Paho.MQTT.Client(host,port,"clientjsaaa");
	//document.write("connecting to "+ host);
	var options = {
        timeout: 3,
		onSuccess: onConnect,
		onFailure: onFailure,


        mqtt.onConnectionLost = onConnectionLost;
        mqtt.onMessageArrived = onMessageArrived;
		mqtt.onConnected = onConnected;

	return false;

	function sub_topics(){
		document.getElementById("messages").innerHTML ="";
		if (connected_flag==0){
		out_msg="<b>Not Connected so can't subscribe</b>"
		document.getElementById("messages").innerHTML = out_msg;
		return false;
	var stopic= document.forms["subs"]["Stopic"].value;
	console.log("Subscribing to topic ="+stopic);
	return false;
	function send_message(){
		document.getElementById("messages").innerHTML ="";
		if (connected_flag==0){
		out_msg="<b>Not Connected so can't send</b>"
		document.getElementById("messages").innerHTML = out_msg;
		return false;
		var msg = document.forms["smessage"]["message"].value;

		var topic = document.forms["smessage"]["Ptopic"].value;
		message = new Paho.MQTT.Message(msg);
		if (topic=="")
			message.destinationName = "test-topic"
			message.destinationName = topic;
		return false;


    <h1>Websockets Using JavaScript MQTT Client</h1>

	    <script type = "text/javascript">

	var connected_flag=0
	var mqtt;
    var reconnectTimeout = 2000;
	var host="";
	var port=1883;


<div id="status">Connection Status: Not Connected</div>
	 <form name="connform" action="" onsubmit="return MQTTconnect()">

Server:  <input type="text" name="server"><br><br>
Port:    <input type="text" name="port"><br><br>
<input type="submit" value="Connect">
<form name="subs" action="" onsubmit="return sub_topics()">
Subscribe Topic:   <input type="text" name="Stopic"><br><br>

<input type="submit" value="Subscribe">
<form name="smessage" action="" onsubmit="return send_message()">

Message: <input type="text" name="message"><br><br>
Publish Topic:   <input type="text" name="Ptopic"><br><br>
<input type="submit" value="Submit">
Messages:<p id="messages"></p>


What errors (if any) are displayed in Chrome’s Developer’s Tools > Console for this page?

I don’t know if it has anything to do with the problem, but the DOCTYPE is XHTML Transitional, yet the markup looks more like HTML5. At least the markup is not valid XHTML (my bet is it isn’t served as XHTML either. Nothing personal, I think most XHTML pages were not served as XHTML)

connecting to 1883 

Firefox can’t establish a connection to the server at ws:// 

Firefox can’t establish a connection to the server at ws:// 


Firefox can’t establish a connection to the server at ws:// 




Are you running this from the filesystem instead of a localhost server? Seeing "file://"s suggests you are opening it by some kind of “right click, open with the default OS browser” instead of putting the pages URL into a browsers address bar and opening it that way.

It wont let me post the whole error because it contains more than 2 links, so ill post it in pieces:

connecting to 1883 websockets-3.htm:82:2

Firefox can’t establish a connection to the server at ws:// mqttws31.js:979:17

Firefox can’t establish a connection to the server at ws:// mqttws31.js:977:17

Failed websockets-3.htm:39:3

Failed websockets-3.htm:39:3
ports websockets-3.htm:71:2
port1883 websockets-3.htm:73:3
host websockets-3.htm:78:3

so I did some research on how websockets work, it looks like I should be using the http port not the mqtt port. So I tried port 80 with no luck. I am running apache 2.4.29, mosquitto and paho on ubuntu 18.04.1.
This is the console log I received using port 80:
connecting to 80 websockets-3.htm:82:2 Firefox can’t establish a connection to the server at ws:// mqttws31.js:979:17 Failed websockets-3.htm:39:3 ports websockets-3.htm:71:2 port80 websockets-3.htm:73:3 host websockets-3.htm:78:3

Perhaps a stupid question but…
Are you sure your MQTT server is running?

I don’t count any question as stupid, statistically people always forget the easy solutions to problems. I did test the mqtt server from multiple machineson my network. I ended up adding some listeners to the mosquitto .conf file and was able to get this working.

listener 1883
protocol mqtt

listener 9001 
protocol websockets
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.