Search code examples
javascriptprototype

How to tell if an object has a given prototype?


How can one detect if a given browser has the searchParams prototype for URL? https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams states that Chrome and FF do but Edge does not, but I wish to detect using JavaScript.

I've messed around with isPrototypeOf, but don't think it is applicable.


Solution

  • In supporting browsers, there will be an URLSearchParams constructor available on global object, so like any other global Constructor,

    'URLSearchParams' in window
    

    or

    typeof window.URLSearchParams === 'function'
    

    and alike will do.

    const support = typeof window.URLSearchParams === 'function';
    console.log('supports URLSearchParams API:', support);
    
    var url = new URL('https://stackoverflow.com/questions/47824782/how-to-tell-if-an-object-has-a-given-prototype?support="true"');
    if(support){
        console.log(url.searchParams.get('support'));
    }