某些URL的Jsdom抛出错误

Lug*_*ino 5 javascript node.js jsdom

我是nodejs的新手,我正在尝试的是扫描我网站的所有网址(启用了javascript和jquery)并检查网址是否包含给定的字符串.

要做到这一点,我使用jsdom,但是当我启动脚本时只提取一些网址,然后崩溃,发出此错误:

timers.js:110
    first._onTimeout();
          ^
TypeError: Property '_onTimeout' of object [object Object] is not a function
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Run Code Online (Sandbox Code Playgroud)

肯定有什么不对,但我不明白在哪里..

这是我的脚本:

var request = require('request');
var jsdom = require('jsdom');

request({ uri: 'http://www.example.com' }, function (error, response, html) {
  if (!error && response.statusCode == 200) {

     var doc = jsdom.jsdom(html, null, {
           features: {
              FetchExternalResources   : ['script'],
              ProcessExternalResources : ['script'],
              MutationEvents           : '2.0',
           }
     });

     var window = doc.createWindow();
     jsdom.jQueryify(window, "http://code.jquery.com/jquery-1.5.min.js", function() {
        var $ = window.jQuery;
        $('a').each(function(i, element){
             var a = $(this).attr('href');
             console.log(a);
             if (a.indexOf('string') != -1) {
               console.log('The winner: '+a);
               //return a;
             }
        });
        window.close();
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

Far*_*hat 3

这是因为在页面的某个地方,他们使用节点不支持的字符串调用 setTimeout/setInterval ,并导致该错误。

要找出它来自哪里,我建议只需要longjohn module( require('longjohn')) 并且您会得到很长的堆栈跟踪,它们将帮助您找到错误。例如,我在 repl 中这样做时得到了类似的结果:

    at listOnTimeout (timers.js:110:15)
---------------------------------------------
    at startTimer (/home/alfred/repos/node_modules/jsdom/lib/jsdom/browser/index.js:75:15)
    at DOMWindow.setTimeout (/home/alfred/repos/node_modules/jsdom/lib/jsdom/browser/index.js:124:50)
    at file:///home/alfred/repos/repl:undefined:undefined<script>:1:1
    at Contextify.sandbox.run (/home/alfred/repos/node_modules/jsdom/node_modules/contextify/lib/contextify.js:12:24)
    at exports.javascript (/home/alfred/repos/node_modules/jsdom/lib/jsdom/level2/languages/javascript.js:5:14)
    at define.proto._eval (/home/alfred/repos/node_modules/jsdom/lib/jsdom/level2/html.js:1523:47)
    at /home/alfred/repos/node_modules/jsdom/lib/jsdom/level2/html.js:76:20
    at item.check (/home/alfred/repos/node_modules/jsdom/lib/jsdom/level2/html.js:345:11)
Run Code Online (Sandbox Code Playgroud)

如果万一这对你不起作用或者你不喜欢它,那么我建议你修改这个 jsdom 文件:node_modules/jsdom/lib/jsdom/browser/index.js,函数 startTimer。callback如果不是函数,则抛出错误。每当运行有问题的代码时都会抛出此错误。

如果您正在运行无法更改的代码(例如来自您不拥有的网站的代码,我不建议这样做,因为类似的外国 JavaScript 可能会被用来攻击您的应用程序),您可以覆盖 DOMWindow.setTimeout /.setInterval 支持字符串参数。您还可以向 jsdom 提出一个问题以选择加入。