Excuse my ignorance. I'm just learning how to use node webkit and was wondering how to fill in form data via a menu item. I'm using the code below and filling in the form data with the 'fill' menu item. However it reports that var elem = document.getElementById("username"); returns null. Any ideas?
var gui = require('nw.gui');
var file = require('file.js');
var menu = new gui.Menu({ type: 'menubar' });
menu.append(new gui.MenuItem({
label: 'File',
submenu: new gui.Menu()
}));
menu.items[0].submenu.append(new gui.MenuItem({
label: 'New',
click: function () {
gui.Window.open('index.html');
}
}));
menu.items[0].submenu.append(new gui.MenuItem({
label: 'fill',
click: function() {
var elem = document.getElementById("username");
elem.value = "myusername";
}
}));
gui.Window.get().menu = menu;
The HTML I'm testing this with is just an html document with one input
<input type="text" id="username">
This is the error I get
Uncaught node.js Error
TypeError: Cannot set property 'value' of null
at MenuItem.menu.items.(anonymous function).submenu.append.gui.MenuItem.click (file:///C:/nodewebkit/js/main.js:22:13)
at MenuItem.handleEvent (menuitem.js:171:12)
at IDWeakMap.global.__nwObjectsRegistry.handleEvent (node.js:795:26)
UPDATE: I don't know if this is relevant but one thing I have noticed is that when I attempt to perform this in the console, i get 'Undefined' when performing
var elem = document.getElementById("username");
However when I enter
elem = document.getElementById("username");
it returns the element just fine. However making that change in the script still leaves me with the same problem.
I ran into the same problem. weirdly enough, using jquery helped me fix it. I have an html page with an image tag with id "close". If I tried using document.getElementById('close') as is, it would always return null. So I wrapped it inside jquery like this:
var nw = require('nw.gui');
var win = nw.Window.get();
$(function(){
var close = document.getElementById('close');
close.onclick = function(){
win.close();
};
});
It started working immediately. Very confused about why nwjs behaves like this.