Adding capability for other browsers to utilize no

2019-08-22 17:36发布

问题:

I would like to add some specific objects, properties, and methods which are not available in all browsers (I am only specifically targeting E11 and Edge). Specifically, I am trying to add Object.assign() and URL.searchParams.get(). I can surely abandon trying to use these methods, and just right my own substitute methods which can be used on all browsers or better yet use a polyfill, but that is not my objective. Please chalk it up to advancing my knowledge (or maybe OCD).

My attempt is below. Object.assign() seems good enough and I even got URL.searchParams.get() working with IE11.

My difficulty is with Edge and URL.searchParams.get(). URL is partially supported so I don't want to override the whole thing like I did with IE11, but only want to add the final searchParams.get() part. How can I detect if this method is supported?

//Crutches for IE and Edge
if(typeof Object.assign !== 'function'){  //IE only
    Object.assign=function(target,source1){
        return [target,source1].reduce(function (r, o) {
            Object.keys(o).forEach(function (k) {
                r[k] = o[k];
            });
            return r;
            }, {});
    }
}

function _get(param) {
    if (!this.params) {
        var params = {};
        var search = decodeURIComponent(window.location.href.slice(window.location.href.indexOf('?') + 1));
        var definitions = search.split('&');
        definitions.forEach(function (val, key) {
            var parts = val.split('=', 2);
            params[parts[0]] = parts[1];
        });
        this.params = params;
    }
    return this.params[param] ? this.params[param] : null;
}
if (typeof URL !== 'function') { //IE only
    URL = function (href) {
        this.href = href;
    }
    URL.prototype.searchParams = {get: _get}
}

if (typeof URL.searchParams !== 'function') { //Edge
//How do I deal with this for Edge as URL is a function ,and URL.searchParams will not even be set for modern browsers
}

console.log(Object.assign({a:'a',b:'b',c:'c'},{a:'A',b:'B',a:'D'}))

var url = new URL(window.location.href);
console.log('pg', url.searchParams.get('pg'));