假设我有window.open(没有名称参数),散布在我的项目中,我想更改实现,以便在未指定名称的地方我将指定默认名称.
我想要做的是将我自己的方法挂钩到window.open,这样每当window.open运行时,它将在内部调用我自己的方法,然后调用window.open(带有name参数).
这可能通过Javascript?在这个窗口中是否会出现循环依赖问题.在调用我的自定义函数时,又调用了window.open函数?
Ps简单来说,我想要做的是覆盖window.open功能.
Ate*_*ral 30
要避免循环调用,您需要将window.open变量中的原始函数存储起来.
一种不错的方法(不污染全局命名空间)是使用闭包.将原始window.open函数作为参数传递给匿名函数(open在下面称为).这个匿名函数是hook函数的工厂.您的钩子函数window.open通过open参数永久绑定到原始函数:
window.open = function (open) {
return function (url, name, features) {
// set name if missing here
name = name || "default_window_name";
return open.call(window, url, name, features);
};
}(window.open);
Run Code Online (Sandbox Code Playgroud)
mpd*_*mpd 10
我知道这个回复有点晚了,但我觉得更通用的解决方案可能对其他人有用(试图覆盖其他方法)
function wrap(object, method, wrapper){
var fn = object[method];
return object[method] = function(){
return wrapper.apply(this, [fn.bind(this)].concat(
Array.prototype.slice.call(arguments)));
};
};
//You may want to 'unwrap' the method later
//(setting the method back to the original)
function unwrap(object, method, orginalFn){
object[method] = orginalFn;
};
//Any globally scoped function is considered a 'method' of the window object
//(If you are in the browser)
wrap(window, "open", function(orginalFn){
var originalParams = Array.prototype.slice.call(arguments, 1);
console.log('open is being overridden');
//Perform some logic
//Call the original window.open with the original params
orginalFn.apply(undefined, originalParams);
});
Run Code Online (Sandbox Code Playgroud)
Ps简单来说,我想要做的是覆盖window.open功能.
var orgOpen = window.open;
window.open = function (...args) {
alert("Overrided!");
return orgOpen(...args);
}
window.open("http://www.stackoverflow.com");
Run Code Online (Sandbox Code Playgroud)