【问题标题】:Monkey patching XMLHttpRequest.prototype.open and "touching" arguments猴子修补 XMLHttpRequest.prototype.open 和“触摸”参数
【发布时间】:2014-12-02 07:13:47
【问题描述】:

我正在尝试为在 IE8 兼容模式下运行的 Intranet 站点打补丁 XMLHttpRequest.prototype.open,但它一直在抛出 SCRIPT438: Object doesn't support this property or method。奇怪的是……如果我先“触摸”arguments,即取消注释bar,它就可以正常工作!有谁知道为什么,如果触摸它确实在 100% 的情况下解决了问题?

var foo = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
  //var bar = arguments;
  foo.apply(this, arguments);
  console.log("OK");
}

这是 IE8 模式下的 IE9modern.ie VM 屏幕截图,带有 Google 图片搜索尝试 open 滚动时的猴子修补请求。

编辑:

console.log(foo);
//console.log(foo.apply);
console.log(typeof foo);
console.log(foo instanceof Function);

返回

LOG: 
function open() {
    [native code]
}

LOG: object 
LOG: false  

console.log(foo.apply) 一扔"Object doesn't support this property or method"

有趣的是,我无法在我尝试的任何模式下在实际的 IE8 VM 中复制它,只能在以 IE8 标准模式运行的 IE9 中复制。

【问题讨论】:

  • 你能做一个console.log(foo, foo.apply, typeof foo, foo instanceof Function)吗?我的猜测是 .apply(this, arguments); 是内部优化的,但“接触”arguments 需要显式创建参数对象。从 Quentin 发现的可能重复项中可以看出,IE 对插件对象的“方法”非常古怪。
  • @Bergi 谢谢,请查看日志返回的编辑。
  • 即使 访问 .apply 它会抛出?哇。但是,是的,这样的事情正是我所担心的。 Function.prototype.apply.call(foo, arguments) 是否可以作为解决方法?
  • 对不起,我忘记了申请的thisArg,它必须是Function.prototype.apply.call(foo, <XHR>, arguments)(在你的例子中<XHR>this)。
  • 嗯……如果您无法装饰它,您似乎需要使用实际的包装器(围绕整个 XMLHttpRequest API):-/

标签: javascript internet-explorer xmlhttprequest monkeypatching


【解决方案1】:
var XHR = XMLHttpRequest.prototype;
XHR.open = function (method, url) {
  //do stuff

  return open.apply(this, arguments);
};

【讨论】:

    【解决方案2】:

    我最近刚刚看到XMLHttpRequest.prototype.open 被覆盖的示例,其方法与您的方法略有不同;

    (function(open) {
        XMLHttpRequest.prototype.open = function() {
            // your special sauce
    
            open.apply(this, arguments);
        };
    })(XMLHttpRequest.prototype.open);
    

    你能检查一下这样做有什么不同吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-13
      • 2013-12-26
      • 2012-06-14
      • 2012-03-29
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      相关资源
      最近更新 更多