Accessing Node-RED msg-Object in the Browser

Using Node-RED you can quickly create good looking dashboards. But sometimes you need more functionality than the included widgets provide. I will show you how you can access the msg-object from your flow from a client-side Javascript. This gives you countless opportunities to create your own widgets.

To reach our goal we use a technique that Node-RED inherits from Angular, which it is based on: the scope. The scope creates the connection between our serverside code and the code that is running in the browser. using the watch function we get notified when changes in the scope occur. In Node-RED we are usually interested in the msg-object that flows between the nodes of our application. Using the following small flow the principle can be easily shown and later adapted to any complex scenario you would like to implement:

  1. Add two inject nodes which insert any value that you like into the flow - in my example the string "Hello World!" and the string "Node-RED rocks!"
  2. Attach a template node from Node-RED Dashbaord to them. The template node must be added to a dashboard page and group.
  3. Insert the following HTML and Javascript code into the template node. This code will be executed in the browser:
<p>msg: <span id="myMsg"></span></p>
 
<script>
(function(scope) {
    // watch msg object from Node-RED
    scope.$watch('msg', function(msg) {
        // new message received
        document.getElementById("myMsg").innerHTML = msg.payload;
    });
})(scope);
</script>

Your flow should now look like this: 

Your dashboard now contains a widget that dynamically shows the text which that you insert into the flow using the inject nodes.

(Visited 680 times, 1 visits today)

Don't want to miss anything?

Newsletter Subscribe Content

* This field is required

About René Auberger 12 Articles
René is an IT Architect for Internet of Things, Industry 4.0, Analytics and Cognitive Computing. In his spare time he makes his house smarter step by step. In 2017 René founded the Internet-of-Things.blog. He is also frequently tweeting. View René's full profile...

2 Comments

    • Hi nazemi,
      did you check that you spelled everything correctly? If document.getElementById returns null then no element was found. Please check that the id of the element is spelled exactly the same as in the HTML element (in case of my example thats "myMsg").

Leave a Reply

Your email address will not be published.


*


+ thirty seven = forty one