如何覆盖window.open功能



假设我有window.open(没有name参数),分散在我的项目中,我想更改实现,以便在没有指定name的地方指定默认名称。

对此,我想做的是将我自己的方法挂接到window.open,这样无论何时windows.open运行,它都会在内部调用我自己的法,然后调用window.open(带有name参数)。

通过Javascript可以做到这一点吗?在这个过程中是否会有任何循环依赖性问题,即window.open调用我的自定义函数,而该函数又再次调用window.open函数?

附言:简单来说,我想做的就是覆盖window.open功能。

为了避免循环调用,需要将原始window.open函数隐藏在一个变量中。

一个不错的方法(不会污染全局命名空间)是使用闭包。将原始window.open函数作为参数传递给匿名函数(下面称为open)。这个匿名函数是钩子函数的工厂。钩子函数通过open参数永久绑定到原始window.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);

我知道这个回复有点晚了,但我觉得一个更通用的解决方案可能对其他人有帮助(试图覆盖其他方法)

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

附言:简单来说,我想做的就是覆盖窗口。打开功能。

var orgOpen = window.open;
window.open = function (...args) {
    alert("Overrided!"); 
    return orgOpen(...args); 
}
window.open("http://www.stackoverflow.com");

最新更新