Home > Software engineering >  using MQTT.js (node package) in electron to update dom
using MQTT.js (node package) in electron to update dom

Time:10-19

I am new to electron and node.js working on mqtt to update the DOM. I receive message on mqtt to my main.js onmessage function and my main.js is

const { app, BrowserWindow } = require('electron')

var mqtt = require('mqtt')
var client = mqtt.connect("mqtt://localhost")

client.on("connect", function(){
client.subscribe("testtopic")
})

client.on("message", function(topic, message, packet){
document.getElementById("someId").innerHTML = message
})

function createWindow () {
  const win = new BrowserWindow({webPreferences:{nodeIntegration: true}})
  win.loadFile('index.html')
  win.maximize()

}
app.whenReady().then(() => {
  createWindow()
})

And I would like to update the element which is available in index.html from my onmessage callback. I cannot access it shows error document is not defined. How to achieve this or can I import mqtt directly in my index.html script ? in that case why use node mqtt instead I can use paho mqtt. Please advice on this.

CodePudding user response:

That code is running in the "backend" not in the browser, so will have no access to the DOM.

If you want update the DOM in response to MQTT messages you have a couple of choices.

  1. Implement a MQTT over WebSockets in the index.html file that will subscribe to the broker directly in the page and will have direct access to the DOM. You can use either the MQTT.js or the Paho client in the page, but you will need a broker that has specifically been configured to support MQTT over WebSockets.

  2. Look at setting up some direct connection between the backend code and the loaded page, the following question might help with some pointers: How to access DOM elements in electron?

  • Related