Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if URL() constructor is supported by browsers?

I want to detect if a browser support the URL() constructor.

I want to use it like this:

const url = new URL(urlString, [baseURLstring])

I can't find a proper method to check if it's supported by browser?

like image 889
David LIu Avatar asked Jun 05 '17 06:06

David LIu


2 Answers

Assuming the check needs to be done in JavaScript -

Use if(typeof URL === "function")

If true URL is supported

Sample Code

if (typeof URL === "function") {
  const baseURLstring = "http://www.aaa.bbb/";
  let urlString = "/hello";
  const url = new URL(urlString, [baseURLstring]);
  console.log(url)
}
else if (navigator.userAgent.indexOf('MSIE') != -1 && typeof URL === 'object') {
  const baseURLstring = "http://www.aaa.bbb/";
  let urlString = "/hello";
  const url = new URL(urlString, [baseURLstring]);
  console.log(url)
}
like image 198
Sushant Salunkhe Avatar answered Oct 26 '22 11:10

Sushant Salunkhe


  1. If const is supported, URL is likely also supported - except
  2. URL is not supported by IE at all it seems
    • https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
    • http://caniuse.com/#feat=url
  3. if (window.URL) ...
like image 36
mplungjan Avatar answered Oct 26 '22 11:10

mplungjan