jsdom:运行页面的javascript函数

时间:2014-05-30 09:35:31

标签: javascript node.js jsdom

我一直在搞乱jsdom,我无法弄清楚如何从html页面运行函数。例如,我有一个这样的简单页面:

<html>
  <body>
    Hello
  </body>
  <script>
    function test() {
      document.write("Bye bye")
    }
  </script>
</html>

我想从jsdom执行test函数。我该怎么做呢?我试过简单地调用该函数,但节点抱怨它不存在。

jsdom.env({
    url : "http://localhost:8000/test.html",
    features : {
        FetchExternalResources : ['script'],
        ProcessExternalResources : ['script']
    },
    done : function (error, window) {
        test(); // I'd like to do something like this.
        console.log(window.document.innerHTML);
    }
});

1 个答案:

答案 0 :(得分:3)

显然,正确的方法是使用window.test()和相应的功能:

jsdom.env({
    url : "http://localhost:8000/test.html",
    features : {
        FetchExternalResources : ['script'],
        ProcessExternalResources : ['script']
    },
    done : function (error, window) {
        window.test();
        console.log(window.document.innerHTML);
    }
});