如何覆盖window.open的功能? [英] How to override the window.open functionality?

查看:147
本文介绍了如何覆盖window.open的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有window.open(没有名称参数),分散在我的项目中,我想更改实现,以便在不指定名称的情况下指定缺省名称。

我想要做的是将我自己的方法挂接到window.open,以便每当window.open运行时,它都会在内部调用我自己的方法,然后调用它自己的方法window.open(带名称参数)。



有可能通过Javascript吗?是否会有任何循环依赖问题,即window.open调用我的自定义函数,然后又调用window.open函数?



P.s。简单地说,我想要做的就是覆盖window.open的功能。

解决方案

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



一种很好的方式(不污染全局命名空间)是使用闭包。将原始的 window.open 函数作为参数传递给一个匿名函数(下面称为 open )。这个匿名函数是您的钩子函数的工厂。你的钩子函数通过打开参数永久地绑定到原始 window.open 函数中:

  window.open = function(open){
返回函数(url,name,features){
// set name if在这里缺少
name = name || default_window_name;
返回open.call(window,url,name,features);
};
}(window.open);


Let's say I have window.open (without name parameter), scattered in my project and I want to change the implementation so that wherever name is not specified I'll specify a default name.

What I want to do about this is hook my own method to window.open so that whenever window.open runs it'll internally call my own method which will then call window.open (with the name parameter).

Is that possible through Javascript? Will there be any circular dependency issues in this i.e. window.open calling my custom function which in turn calling the window.open function again?

P.s. In simple terms what I want to do is override the window.open functionality.

解决方案

To avoid circular calls, you need to stash away the original window.open function in a variable.

A nice way (that doesn't pollute the global namespace) is to use a closure. Pass the original window.open function to an anonymous function as an argument (called open below). This anonymous function is a factory for your hook function. Your hook function is permanently bound to the original window.open function via the open argument:

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

这篇关于如何覆盖window.open的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆