How to override the window.open functionality?

前端 未结 3 1533
走了就别回头了
走了就别回头了 2020-12-07 23:38

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

3条回答
  •  失恋的感觉
    2020-12-08 00:16

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

提交回复
热议问题