Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - How to override the window.open functionality?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...