Using window.open in function node


#1

I'm trying to create a links section on my dashboard. So, I've got a button that I want to simply cause a particular website to open in a new browser tab (not a ui tab). I'm trying to use the function node after my button node with the following code. But, it's giving me the following error.

var redirectURL = msg.payload;
var myWindow = window.open(redirectURL, '_blank');

ReferenceError: window is not defined (line 2, col 16)


#2

Hi @mooreb

the Function node runs in the Node-RED runtime where there is no browser to do anything with.

To open a new browser window you need to run some code inside the browser. To do that could use a ui_template to add some code to the dashboard that can trigger opening a window when a message is received.


#3

@knolleary

Ah I see, that makes sense. Thanks for explaining that! Sorry, I'm pretty new to all this. Could you possibly give me an example of the code that I'd need to run in a ui_template node? Also, is there a way to hide that ui_template node, so it doesn't show up anywhere?


#4

Seems a bit "heavy" to use a function node to tell the dashboard to open a plain html page... and I don't see any good options in the flows library. This may be a good candidate for a new "open web page" contrib node -- but I digress.

If the "Links" section of your dashboard is plain HTML <a target="_blank" href="..."> tags, the browser will open those sites without involving any node-red function or other nodes.

As Nick says, use a ui_template node to render the html links -- and since you can use "mustache" substitution, it's easy to send a msg with an array of links to that ui_template node to have it dynamically rendered, something like this (untested):

<div id="my_links">
  {{#payload}}
    <a target="_blank" href="{{url}}">{{label}}</a>
  {{/payload}}
</div>

This syntax expects an incoming msg.payload with an array of link objects, each with its url and label, like this:

{
    "payload": [
        { "label": "Site 1", "url": "http://site1.com" },
        { "label": "Site 2", "url": "http://site2.com" }
    ]
}

#5

If you are using a dashboard button as you mention, you can insert the link directly in its label field such as:

If you don't need the button, you can use the Text node and insert the links in the value format field like:


#6

@hugobox, @shrickus,
Awesome guys, thanks!!!! It's all starting to make sense to me now. I got it working. I like the built in dashboard buttons, so I used hugobox's solution to pass the URL and Label into the ui_template, which is using shrickus's solution. And, thanks to knolleary for helping me understand why my initial solution wasn't working. Thanks also for everyone's patience with me. We all have to start somewhere, right? lol