Phantomjs Function.prototype.bind

时间:2014-12-26 16:32:20

标签: javascript phantomjs

是的,我知道。 Phantomjs不支持函数绑定。但也许我可以使用别的东西,或者说page.open不要使用bind?它似乎没问题,但有些网站 返回错误

TypeError: 'undefined' is not a function (evaluating 'b.bind(a)')

之后我写了一个简单的脚本,只打开一个页面:

var address = phantom.args[0];
if(!address) phantom.exit(1);

page = require("webpage").create();

page.open(address, function(status){
setInterval(
   function () {

   console.log(
       page.evaluate(function() {
            return document.body.innerHTML.length;
       })
   )}, 200)
})

但错误仍然存​​在。错误不是主要问题,但问题是获取页面内容,因为错误页面内容未加载...

所以,我需要帮助。

P.S。问题网站是http://vkrushelnytskiy.wix.com/aaaa

4 个答案:

答案 0 :(得分:7)

有一个npm package which loads a polyfill for phantomJS's missing .bind method。为方便起见,请在此处复制安装说明,但请按照链接进行更新。

<强>安装

npm install --save-dev phantomjs-polyfill

<强>用法

require('phantomjs-polyfill')

使用Karma 将polyfill直接包含在karma.conf的文件列表中

...
files: [
  './node_modules/phantomjs-polyfill/bind-polyfill.js',
  ...
]
...

答案 1 :(得分:2)

You can use this code as an alternative

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

答案 2 :(得分:1)

您可以使用以下polyfill来填充Function.bind。

只需将其添加到您尝试运行的代码中。可能有更好的解决方案,但这对我来说很有用。

答案 3 :(得分:1)

您可以在测试用例之前提及此绑定函数。

// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind ||
  function (ctx) {
    var fn = this,
      args = [],
      param_length = 0;

  for(var i=0; i<arguments.length; i++) {    
    if(i){
      args[i-1] = arguments[i];
    }
  }
  param_length = args.length;
  return function () {
    for(var i =0; i<arguments.length; i++){
      args[param_length + i] = arguments[i];
    }
    return fn.apply(ctx, args);
  };
};
相关问题