Import global variable for use in Java Script

I am trying to add an object to the tool bar that contains text and variable I set in the flow. The script below has the test section that I am having issues with. I have figured out how to post a variable with text that I configure in the script. However I want to use a global variable that is set from a flow. Here is the context view of the variable confirming its existance:
image

I have tried var kpi = global.get("kdx") and var kpi = globalContext.get("kdx"). When I add that line the script blows up.

I am running node.js ver v14.17.2 and Node-RED v2.0.1

Please advise on the proper way to import global variables to use in a java script.

<script id="clockScript1" type="text/javascript">
    var clockInterval;
    $(function () {
        if (clockInterval) return;

        //add logo
        var div1 = $('<div/>');
        var logo = new Image();

        logo.src = '/svarclogotp.png'
        logo.height = 40;
        div1[0].style.margin = '0px auto';
        div1[0].style.align - 'center';
       
        div1.append(logo);

        //test
        var kpi = "KPi";
        var div2 = $('<div/>');
        var p1 = $('<p/>');
        div2[0].style.margin = '0px auto';
        div2[0].style.align - 'center';
        div2.append(p1).text(kpi);
       
       
        // add clock
        var div3 = $('<div/>');
        var p = $('<p/>');

        div3.append(p);
        div3[0].style.margin = '0px';    
        
        

        
        function displayTime() {
            var d = Date();
            var options = { timeZone: 'UTC', timeZoneName: 'short',  hourCycle: 'h23', hour: `2-digit`, minute: `2-digit`};
            p.text(new Date().toLocaleString('en-US', options));
        }
        
        clockInterval = setInterval(displayTime, 1000);

        //add to toolbar when it's available
        var addToToolbarTimer;
        
        function addToToolbar() {
            var toolbar = $('.md-toolbar-tools');
            
            if(!toolbar.length) return;
            
            toolbar.append(div1);
            toolbar.append(div2);
            toolbar.append(div3);
            clearInterval(addToToolbarTimer);
        }
        addToToolbarTimer = setInterval(addToToolbar, 100);
    });
</script>

This looks like client side code - context is server side.

You will need to pass it from server side (flows) to client side (dashboard). How this is done depending on how you have that script set up in your flow.

Can you share your flow?

Can you explain where / how you want to use this context value?

Here is the flow. Pretty basic fetching json datg NOAA wx. As far as use. I want to populate the variable in the toolbar. If you look at the test section that was my attempt. I can get it to populate the variable if I assign the string in the code. Here is the current view of the setup. Formatting is off. Not to much worried about that yet:

[{"id":"6a8d55e7.251cfc","type":"inject","z":"11cbc96d.686597","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"300","crontab":"","once":true,"onceDelay":"5","topic":"","payload":"","payloadType":"date","x":110,"y":380,"wires":[["5a9528bb.71cd78","a05b35a9.43daf8","567f6f5f.5861f","448a88e5.a96dd8"]]},{"id":"5a9528bb.71cd78","type":"http request","z":"11cbc96d.686597","name":"kp_index","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://services.swpc.noaa.gov/json/planetary_k_index_1m.json","tls":"","persist":false,"proxy":"","authType":"","x":280,"y":280,"wires":[["72308fb9.0e687"]]},{"id":"72308fb9.0e687","type":"json","z":"11cbc96d.686597","name":"","property":"payload","action":"obj","pretty":false,"x":430,"y":280,"wires":[["462f352d.db43ec","ac91594.bc0cba8"]]},{"id":"ac91594.bc0cba8","type":"function","z":"11cbc96d.686597","name":"","func":"var kpi = msg.payload[msg.payload.length-1].kp_index;\nmsg1 = {topic: \"Kpi\", payload: kpi};\n\nnode.send([msg1]);\n\n\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":580,"y":280,"wires":[["9bd421e8.7d2c7","76be697a.2d7018"]]},{"id":"9bd421e8.7d2c7","type":"ui_chart","z":"11cbc96d.686597","name":"","group":"f15febe0.9de5c8","order":4,"width":0,"height":0,"label":"Kpi","chartType":"line","legend":"false","xformat":"HH:mm","interpolate":"linear","nodata":"No Data Available","dot":true,"ymin":"","ymax":"","removeOlder":"12","removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":true,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"x":750,"y":280,"wires":[[]]},{"id":"f15febe0.9de5c8","type":"ui_group","name":"Solar","tab":"53ba0b2c.da2874","order":2,"disp":true,"width":"6","collapse":false},{"id":"53ba0b2c.da2874","type":"ui_tab","name":"Solar","icon":"dashboard","order":9,"disabled":false,"hidden":false}]

You haven't included the part that build the top bar clock (that is where this should be added)

PS, if you dont press the reply button under my response (but press the general reply button at the bottom of the thread instead) I dont know you have replied.

Steve thanks for helping out. Below is the flow where the toolbar is coded. see the test section.

[{"id":"37281d3.63445e2","type":"ui_template","z":"66bcebdf.285414","group":"26d30615.80273a","name":"Logo / Clock","order":0,"width":0,"height":0,"format":"<script id=\"clockScript1\" type=\"text/javascript\">\n    var clockInterval;\n    $(function () {\n        if (clockInterval) return;\n\n        //add logo\n        var div1 = $('<div/>');\n        var logo = new Image();\n\n        logo.src = '/svarclogotp.png'\n        logo.height = 40;\n        div1[0].style.margin = '0px auto';\n        div1[0].style.align - 'center';\n       \n        div1.append(logo);\n\n        //test\n        var kpi = \"KPi\";\n        var div2 = $('<div/>');\n        var p1 = $('<p/>');\n        div2[0].style.margin = '0px auto';\n        div2[0].style.align - 'center';\n        div2.append(p1).text(kpi);\n       \n       \n        // add clock\n        var div3 = $('<div/>');\n        var p = $('<p/>');\n\n        div3.append(p);\n        div3[0].style.margin = '0px';    \n        \n        \n\n        \n        function displayTime() {\n            var d = Date();\n            var options = { timeZone: 'UTC', timeZoneName: 'short',  hourCycle: 'h23', hour: `2-digit`, minute: `2-digit`};\n            p.text(new Date().toLocaleString('en-US', options));\n        }\n        \n        clockInterval = setInterval(displayTime, 1000);\n\n        //add to toolbar when it's available\n        var addToToolbarTimer;\n        \n        function addToToolbar() {\n            var toolbar = $('.md-toolbar-tools');\n            \n            if(!toolbar.length) return;\n            \n            toolbar.append(div1);\n            toolbar.append(div2);\n            toolbar.append(div3);\n            clearInterval(addToToolbarTimer);\n        }\n        addToToolbarTimer = setInterval(addToToolbar, 100);\n    });\n</script>","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":false,"templateScope":"global","x":290,"y":160,"wires":[[]]},{"id":"26d30615.80273a","type":"ui_group","name":"ToolBar","tab":"f4b91d3a.a7533","order":1,"disp":false,"width":"24","collapse":false},{"id":"f4b91d3a.a7533","type":"ui_tab","name":"Home","icon":"home","order":1,"disabled":false,"hidden":false}]

The key to this is to transmit from server side to client side. for that to work, the value has to be sent to front end via a template node set on a tab (not head)

Have a look at the below flow to understand how its put together

image

[{"id":"6a8d55e7.251cfc","type":"inject","z":"1683bd9a.5e0a02","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":"5","topic":"","payloadType":"date","x":860,"y":1840,"wires":[["5a9528bb.71cd78"]]},{"id":"5a9528bb.71cd78","type":"http request","z":"1683bd9a.5e0a02","name":"kp_index","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://services.swpc.noaa.gov/json/planetary_k_index_1m.json","tls":"","persist":false,"proxy":"","authType":"","x":1020,"y":1840,"wires":[["ac91594.bc0cba8"]]},{"id":"ac91594.bc0cba8","type":"function","z":"1683bd9a.5e0a02","name":"","func":"var kpi = msg.payload[msg.payload.length-1].kp_index;\nmsg.topic = \"kpi\";\nmsg.payload = kpi;\nreturn msg;\n\n\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1180,"y":1840,"wires":[["9486fb36a6b24e46","4b689f7473831a84"]]},{"id":"9486fb36a6b24e46","type":"debug","z":"1683bd9a.5e0a02","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":1350,"y":1880,"wires":[]},{"id":"37281d3.63445e2","type":"ui_template","z":"1683bd9a.5e0a02","group":"26d30615.80273a","name":"Logo / Clock","order":0,"width":0,"height":0,"format":"<script id=\"clockScript1\" type=\"text/javascript\">\n    var clockInterval;\n    $(function () {\n        if (clockInterval) return;\n\n        //add logo\n        var div1 = $('<div/>');\n        var logo = new Image();\n\n        logo.src = '/svarclogotp.png'\n        logo.height = 40;\n        div1[0].style.margin = '0px auto';\n        div1[0].style.align - 'center';\n       \n        div1.append(logo);\n\n        //test\n\n        var div2 = $('<div/>');\n        var p1 = $('<span>KPi</span>');\n        var p2 = $('<span id=\"header-kpi\">...</span>');\n        p1[0].style.margin = '0px 2px';\n        p2[0].style.margin = '0px 2px'; \n        div2[0].style.margin = '0px auto';\n        div2[0].style.align - 'center';\n        div2.append(p1);\n        div2.append(p2);\n       \n       \n        // add clock\n        var div3 = $('<div/>');\n        var p = $('<p/>');\n\n        div3.append(p);\n        div3[0].style.margin = '0px';    \n        \n        \n\n        \n        function displayTime() {\n            var d = Date();\n            var options = { timeZone: 'UTC', timeZoneName: 'short',  hourCycle: 'h23', hour: `2-digit`, minute: `2-digit`};\n            p.text(new Date().toLocaleString('en-US', options));\n        }\n        \n        clockInterval = setInterval(displayTime, 1000);\n\n        //add to toolbar when it's available\n        var addToToolbarTimer;\n        \n        function addToToolbar() {\n            var toolbar = $('.md-toolbar-tools');\n            \n            if(!toolbar.length) return;\n            \n            toolbar.append(div1);\n            toolbar.append(div2);\n            toolbar.append(div3);\n            clearInterval(addToToolbarTimer);\n        }\n        addToToolbarTimer = setInterval(addToToolbar, 100);\n    });\n</script>","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":false,"templateScope":"global","className":"","x":1350,"y":1800,"wires":[[]]},{"id":"4b689f7473831a84","type":"ui_template","z":"1683bd9a.5e0a02","group":"dce9e7a2.d20c78","name":"update KPI","order":7,"width":0,"height":0,"format":"\n<script>\n    (function(scope) {\n        //hide this card. NOTE: 4b689f7473831a84 is the Node id as \n        //seen in the INFO panel on the sidebar when you select this node\n        $('[node-id=\"4b689f7473831a84\"]').hide();\n        scope.$watch('msg', function(msg) {\n            if (msg && msg.topic == \"kpi\") {\n                $(\"#header-kpi\").text(msg.payload);\n            }\n        });\n    })(scope);\n</script>\n","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":true,"templateScope":"local","className":"","x":1350,"y":1840,"wires":[[]]},{"id":"26d30615.80273a","type":"ui_group","name":"ToolBar","tab":"f4b91d3a.a7533","order":1,"disp":false,"width":"24","collapse":false},{"id":"dce9e7a2.d20c78","type":"ui_group","name":"Object detection","tab":"5132060d.4cde48","order":1,"disp":true,"width":"9","collapse":false},{"id":"f4b91d3a.a7533","type":"ui_tab","name":"Home","icon":"home","order":1,"disabled":false,"hidden":false},{"id":"5132060d.4cde48","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]
1 Like

Steve,
I thought I had it but I have this one last issue. I deployed the node that you sent. I can see where yours works fine. Mine however shows this...
image

I disabled all my nodes and reimported your flow into a new flow tab and still see the same thing. I thought that maybe I did not have the node hidden correctly. The flow imported from you has the same node id so not really sure what going on.

Regards

I disabled the request on the inject.

Have you clicked the inject node button?

Does the node id match the id in the template?

I just figured it out. I had it deployed in the wrong group...Thank you sir for you help.

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