Phantomjs Function.prototype.bind

Phantomjs Function.prototype.bind

本文关键字:bind prototype Function Phantomjs      更新时间:2023-09-26

是的,我知道。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)
})

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

所以,我需要帮助。

附言问题网站 http://vkrushelnytskiy.wix.com/aaaa

有一个 npm 包,它为 phantomJS 缺少的 .bind 方法加载一个 polyfill。为方便起见,请在此处复制安装说明,但请按照链接获取任何更新。

安装

npm install --save-dev phantomjs-polyfill

用法

require('phantomjs-polyfill')

与业力一起使用将 polyfill 直接包含在您的 karma.conf 的文件列表中

...
files: [
  './node_modules/phantomjs-polyfill/bind-polyfill.js',
  ...
]
...
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;
  };
}

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

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

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

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