【问题标题】:node-webkit website test utilitynode-webkit 网站测试工具
【发布时间】:2015-02-27 11:00:15
【问题描述】:

我正在尝试使用 nw.js 构建一个工具,该工具可以打开网站窗口、加载 jQuery 库并使用参数运行脚本,例如验证页面标题文本并将结果返回到主脚本。任何人都可以提供有效代码的示例吗?

【问题讨论】:

    标签: node.js node-webkit nw.js


    【解决方案1】:

    我尝试做到这一点,当我打开通常的窗口并尝试调用win.eval 它在documentation 中的说法时它不起作用。但我可以访问所有子窗口对象。

    我发现有一个选项:inject-js-end,它允许我们在页面中注入本地文件。

    我将注入的这个文件示例:

    // 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();
    

    然后我们可以打开任何 url 并注入我们的检查器:

    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);
      });
    });
    

    你应该能够看到类似的东西:

    [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)
    

    可能你想在checker.js 中添加 jQuery 并做一些不同的事情,所以最好让它异步返回结果。

    我使用“inject-js-end”来确保在我运行检查器时所有内容都准备就绪,它也可以与“inject-js-start”一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      相关资源
      最近更新 更多