Javascript Monkey修补了一个命名函数';他马上打电话来
我正在加载的脚本行为不正常。它的结构是这样的:Javascript Monkey修补了一个命名函数';他马上打电话来,javascript,monkeypatching,Javascript,Monkeypatching,我正在加载的脚本行为不正常。它的结构是这样的: function bad_function() { ... } /* randomly generated stuff */ bad_function(); 如果在脚本末尾立即调用bad_函数,如何修改该函数的行为?我想在加载脚本之前在窗口上创建一个静默只读属性,但这会引发类型错误:执行上述脚本时,标识符“bad_function”已声明为异常: Object.defineProperty(window, 'bad_function'
function bad_function() {
...
}
/* randomly generated stuff */
bad_function();
如果在脚本末尾立即调用bad_函数
,如何修改该函数的行为?我想在加载脚本之前在窗口
上创建一个静默只读属性,但这会引发类型错误:执行上述脚本时,标识符“bad_function”已声明为异常
:
Object.defineProperty(window, 'bad_function', {
value: function() {
/* my monkey-patched code */
}
});
如何对该函数进行修补?这不太好,但我所能做的就是通过ajax加载脚本,而不是将其放入
标记中,操作结果字符串以调用您自己的函数版本(或“重命名”bad_函数
,这样它就不会覆盖您的版本),然后将其放入
标记中,并将其附加到页面:
为了简单起见,使用jQuery的示例如下:
function good_function() {
alert("I am good");
}
$.ajax({
url: '/echo/html/',
type: 'POST',
data: {
html: "function bad_function() { alert('hahaha'); } bad_function();",
delay: 0
},
success: function(data) {
console.log(data);
// comment this line to see the original
data = data.replace('bad_function();', 'good_function();')
var newScript = $('<script type="text/javascript" />').text(data);
$('body').append(newScript);
}
});
功能良好\u功能(){
警惕(“我很好”);
}
$.ajax({
url:“/echo/html/”,
键入:“POST”,
数据:{
html:“函数bad_function(){alert('hahaha');}bad_function();”,
延迟:0
},
成功:功能(数据){
控制台日志(数据);
//注释此行以查看原始内容
data=data.replace('bad_function();','good_function();')
var newScript=$('').text(数据);
$('body').append(newScript);
}
});
虽然这不是对我的问题的一般回答,但我能够通过修补函数内部调用的全局函数(如
encodeURIComponent
),执行必要的更改,并引发异常以阻止原始函数的其余部分运行,从而对我的特定函数进行修补
var old_encodeURIComponent = window.encodeURIComponent;
window.encodeURIComponent = function() {
// If this function is used in multiple places, look for variables in
// the current scope to determine if this is the right spot to start
// monkey patching.
if (typeof a === 'undefined' || typeof b === 'undefined') {
return old_encodeURIComponent.apply(this, arguments);
}
// You now have access to the variables in the scope of your target
// function. If your monkey patching is just a simple tweak, you're all set
// Otherwise, do what you need to do and throw an exception to stop the
// rest of the code from running
throw 'goodbye';
};
重命名
bad_函数
将破坏猴子补丁的全部功能。您使用的是Chrome吗?这是您所面临的特定于浏览器的问题吗?@jk_查尔斯:不,这与浏览器无关,并且是脚本的问题。您是在与原始bad_函数()相同的JS文件中使用“defineProperty”,还是在不同的文件中使用?如果是不同的文件,标签的排列顺序是什么?@jk_查尔斯:我不能修改包含坏函数的脚本,但我可以修改加载它的页面。