javascript - Monkey Patch jquery 函数内容

标签 javascript jquery

预先感谢您的帮助。

我正在尝试对现有的 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 的第一行是在服务器端动态创建的,因此该属性可以设置为关闭。

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

虽然很讨厌,但我想重新定义该函数,替换 HTMLtoPDF 文本以指向新页面。

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

function($){

            var _oldPrint = $.fn.GoPrint;

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

有什么建议吗?

最佳答案

一种方法是在旧函数上调用 toString,将旧 URL 替换为新 URL,然后评估结果,但前提是要考虑安全隐患。

纯粹从安全 Angular 来看,更安全的方法是在 GoPrint 的猴子补丁中对 window.open 函数进行猴子补丁。

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

关于javascript - Monkey Patch jquery 函数内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261250/

相关文章:

javascript - 如何对齐具有不同列数的两行

javascript - SAPUI5/Javascript 如何将二进制数据转换为可读格式并下载为 PDF

javascript - 理解 Jquery 代码以突出显示导航栏项目

javascript - Kendo UI 验证 - 禁用/启用

javascript - 将数字转换为对应的字母

c# - 保存静态信息的表的名称是什么

javascript - 停止创建div时Jquery可拖动

javascript - 修改iframe属性

javascript - Jquery 插件对象 #<HTMLDocument> 没有方法 'observe' 问题

javascript - PushState 改变浏览器 URL 后刷新页面;它告诉我页面不存在