Search code examples
node.jseventsnode-webkitemit

How to share data between windows in Node Webkit?


I am using node webkit v0.45, and am need to open a new window (with a pre-determined html layout) with dynamic parameters.

The only documentation I can find suggests using on "loaded" event to emit data to the new window, and then handle the data that is received using on "data" in the new window html, as per below:

Main window:

var ngui = require('nw.gui');

var newWindow = ngui.Window.open('newwindow.html', {
    width: 1120,
    height: 360
})

newWindow.on ('loaded', function(){
    var data = {msg: "test"};
    newWindow.emit("data", data);
});

New window:

var gui = require('nw.gui');
var win = gui.Window.get();
win.on("data", function(data) {
    console.log(data.msg);
});

However, it seems after v0.13 this was deprecated and the Window class is no longer inherited from EventEmitter. Are there any other options for opening windows with parameters?

*** Update ***

The following code will work when the new window is opened:

var param = 'param';
ngui.Window.open('newWindow.html', {
    width: 1120,
    height: 360,
}, function(newWindow) {
    pageWindow.on('loaded', () => {
        newWindow.window.param = param;
    });
});

And in newWindow.html:

<script>
    function getParam(){
        if (!window.param){
            setTimeout(function(){
                getParam();
            },50);
        } else {
            console.log("Successfully loaded param: '" + window.param + "'");
        }
    }
    getParam();
</script>

Solution

  • The Node context can be used to share data, as the Node context is shared across windows.