Monkey Patch jquery函数内容

时间:2014-12-02 23:53:37

标签: javascript jquery

提前感谢您的帮助。

我正在尝试monkeypatch现有的javascript函数,以便其中一行指向一个新位置。重新定义该函数很容易,除了它是从具有动态内容的服务器端代码呈现的。

function GoPrint() {
    $.cookie('edit_child','on',{expires:28,path:'/'}); //Dynamically created (edit child could be off)
    window.open('../../Common/Output/HTMLtoPDF.aspx','print'); //Always static, need to change this call.
}

在我的示例中,创建cookie的第一行是动态创建的服务器端,因此可以将属性设置为off。

我需要更改window.open以调用不同的页面而不是htmltopdf页面。

虽然很讨厌,但我想重新定义HTMLtoPDF文本中的替换功能以指向新页面。

我已在下面开始,但不知道如何获取该函数的现有内容来更改它。

function($){

            var _oldPrint = $.fn.GoPrint;

            $.fn.GoPrint = function(arg1,arg2){
                   return _oldPrint.call(this,'',);
            };
        })(jQuery);

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是在旧函数上调用toString,使用新函数调用旧URL,并评估结果,但仅在考虑安全隐患后。

纯粹在安全方面,更安全的方法是在window.open的猴子补丁中修补GoPrint函数。

function($) {

  var _oldPrint = $.fn.GoPrint;

  $.fn.GoPrint = function(arg1, arg2) {
    var _oldopen = window.open;

    window.open = function() {
      _oldopen.call('YOUR_URL_HERE', 'print');
    };

    return _oldPrint.call(this);

    window.open = _oldopen;
  };
})(jQuery);