Search code examples
javascriptnode-red

run javascript function using msg.payload in node-red


I have a javascript code inside a template node in node-red, this code is a simple progress bar. It's quiet easy to run the javascript function the button of the html code, but I'd like to run the code when a payload arrives... and then I'd like to send a new payload when width is equal to 95...

My idea is to run this code : msg.payload === 0 ? move() : '' to run move() when my payload is equal to 0. But I have no idea where to write it.

Then I tryed to assign the value 1 to my payload when witdh is equal to 95 but not working... for sure I am not using the good syntax.. A bit lost to interact with this template node in node-red.

<!DOCTYPE html>
<html>
<style>
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 100%;
  height: 30px;
  background-color: #4CAF50;
}
</style>
<body>

<h1>JavaScript Progress Bar</h1>

<div id="myProgress">
  <div id="myBar"> </div>
</div>
  <p id="msg">  </p>

  <button onclick="move()">Click Me</button> 

<br>


<script>
var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var message = document.getElementById("msg");
    var width = 100;
    var id = setInterval(frame, 100);
    function frame() {
      if (width <= 0) {
        clearInterval(id);
        i = 0;
      } else {
        width = width - 1;
        elem.style.width = width + "%";
        elem.textContent = width;
        if (width == 95) {
            message.textContent = "forcez";
            {payload: 1};

        }

      }
    }
  }
}
</script>

</body>

Solution

  • Perhaps you know this already, but let me repeat here as many people don't know or have forgotten it.

    Your Node-RED flow runs as a Node.js application in a server (back end).

    The JavaScript code inside the script tags runs in the browser.

    The code in the browser can not directly read a message from or send a message to the ui_template in the runtime.

    (a) Sending a message from the runtime to the code running in the browser.

    The solution is wrapping your function around this function:

    (function(scope){
         scope.$watch('msg',function(){
              ...
       })
    })(scope)
    

    (b) send an object from the code running in the browser to the runtime.

    The scope object has a send function that can be used to send a message from the ui_template node within the runtime.

    You want to use this statement: scope.send(msg), e.g: scope.send({topic : "topic", payload : "payload"})

    In your specific case you will need to add these lines to the code in the ui_template

    <script>
    (function(scope) {
        // $watch fires each time the node is triggered in the flow
        scope.$watch('msg', function(msg) {
                if (msg.payload == 0) {
                    move();
                }
            });
    
    .............
    
    })(scope);
    </script>
    

    also

     if (width == 95) {
        message.textContent = "forcez";
        scope.send({payload:"warning: width 95"});
    
     }
    
    

    A few other changes may be needed to your sample flow, e.g. a protection to avoid it from running twice when the ui_template receives a new payload when it is still counting down.

    Here an attempt to implement those changes in your sample code:

    [{"id":"dba00648.b7f6d8","type":"tab","label":"Flow 12","disabled":false,"info":""},{"id":"4cc372c7.58d5ac","type":"ui_template","z":"dba00648.b7f6d8","group":"5af14c6e.d86604","name":"","order":5,"width":0,"height":0,"format":"<!DOCTYPE html>\n<html>\n<style>\n#myProgress {\n width: 100%;\n background-color: #ddd;\n}\n\n#myBar {\n width: 100%;\n height: 30px;\n background-color: #4CAF50;\n}\n</style>\n<body>\n\n\n<div id=\"myProgress\">\n <div id=\"myBar\"> </div>\n</div>\n <p id=\"msg\"> {{msg.payload}} </p>\n \n\n\n<br>\n\n\n<script>\n\n(function(scope) {\n    // $watch fires each time the node is triggered in the flow\n    scope.$watch('msg', function(msg) {\n            if (msg.payload == 0) {\n                move();\n            }\n        });\n\nvar i = 0;\nfunction move() {\n if (i == 0) {\n i = 1;\n var elem = document.getElementById(\"myBar\");\n var message = document.getElementById(\"msg\");\n message.textContent = \"start\";\n var width = 100;\n var id = setInterval(frame, 100);\n \n function frame() {\n if (width <= 0) {\n clearInterval(id);\n i = 0;\n } else {\n width = width - 1;\n elem.style.width = width + \"%\";\n elem.textContent = width;\n if (width == 95) {\n \tmessage.textContent = \"forcez\";\n \tscope.send({payload:\"warning: width 95\"});\n \n }\n \n }\n }\n }\n}\n\n})(scope);\n</script>\n\n</body>","storeOutMessages":true,"fwdInMessages":true,"templateScope":"local","x":440,"y":240,"wires":[["9779fd5e.1d736"]]},{"id":"9779fd5e.1d736","type":"debug","z":"dba00648.b7f6d8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":610,"y":240,"wires":[]},{"id":"dde1582.3b84ca8","type":"inject","z":"dba00648.b7f6d8","name":"","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":240,"wires":[["4cc372c7.58d5ac"]]},{"id":"72ccb344.ed011c","type":"inject","z":"dba00648.b7f6d8","name":"","topic":"","payload":"1","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":280,"wires":[["4cc372c7.58d5ac"]]},{"id":"5af14c6e.d86604","type":"ui_group","z":"","name":"Compte à rebours","tab":"7560e5e8.ee7dfc","order":3,"disp":true,"width":"6","collapse":false},{"id":"7560e5e8.ee7dfc","type":"ui_tab","z":"","name":"Préhension SELFIT","icon":"dashboard","order":4,"disabled":false,"hidden":false}]
    

    References:

    https://flows.nodered.org/flow/2f1aaf0635f9bf23207152682323240a

    How to store a msg.payload into a script variable inside a ui_template node red?