Search code examples
node.jsnode-webkitnw.js

node-webkit website test utility


I'm trying to build a tool using nw.js which can open website window, load jQuery library, and run script with parameters, for e.g. validate page title text and return results back to main script. Can anyone give a sample of valid code?


Solution

  • I try to make it, when I open usual window and try to call win.eval how it says in documentation it don't work. But I can access all child window objects.

    I find there is option: inject-js-end, it allows us to inject local file in page.

    This example of file I will inject:

    // checker.js
    // this file will run in newly opened page.
    console.log("checker loaded");
    window.myChecker = {
      listeners: [],
    
      done: function (callback) {
        if (this.result) callback(this.result);
        else this.listeners.push(callback);
      },
    
      start: function () {
        this.result = {a: 123, title: document.title};
        this.listeners.forEach(function (fn) { fn(this.result); });
      }
    };
    
    myChecker.start();
    

    Then we can open any url and inject our checker:

    var win = gui.Window.open('https://github.com', {
      show: true, // make it false to make window hidden
      "inject-js-end": "./checker.js"
    });
    
    win.on('loaded', function () {
      console.log("window loaded");
      win.window.myChecker.done(function (result) {
        console.log("Result is", result);
      });
    });
    

    You should be able to see something like:

    [87518:0301/142832:INFO:CONSOLE(1)] ""checker loaded"", source:  (1)
    [87518:0301/142835:INFO:CONSOLE(107)] ""window loaded"", source: file:///my_path/index.js (107)
    [87518:0301/142835:INFO:CONSOLE(109)] ""Result is" {"a":123,"title":"GitHub \u00B7 Build software better, together."}", source: file:///my_path/index.js (109)
    

    Probably you want to add jQuery in checker.js and do some different things, so better make it return result asynchronous.

    I use "inject-js-end" to make sure all content is ready at time I run checker, it also can work with "inject-js-start".