How to override the window.open functionality?

前端 未结 3 1534
走了就别回头了
走了就别回头了 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-07 23:56

    I know this reply is a little late, but I felt that a more general solution may be helpful for other people (trying to override other methods)

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

提交回复
热议问题