resolve-url.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import URLToolkit from 'url-toolkit';
  2. import window from 'global/window';
  3. var DEFAULT_LOCATION = 'http://example.com';
  4. var resolveUrl = function resolveUrl(baseUrl, relativeUrl) {
  5. // return early if we don't need to resolve
  6. if (/^[a-z]+:/i.test(relativeUrl)) {
  7. return relativeUrl;
  8. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  9. if (/^data:/.test(baseUrl)) {
  10. baseUrl = window.location && window.location.href || '';
  11. } // IE11 supports URL but not the URL constructor
  12. // feature detect the behavior we want
  13. var nativeURL = typeof window.URL === 'function';
  14. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  15. // and if baseUrl isn't an absolute url
  16. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  17. if (nativeURL) {
  18. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  19. } else if (!/\/\//i.test(baseUrl)) {
  20. baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  21. }
  22. if (nativeURL) {
  23. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  24. // and if we're location-less, remove the location
  25. // otherwise, return the url unmodified
  26. if (removeLocation) {
  27. return newUrl.href.slice(DEFAULT_LOCATION.length);
  28. } else if (protocolLess) {
  29. return newUrl.href.slice(newUrl.protocol.length);
  30. }
  31. return newUrl.href;
  32. }
  33. return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  34. };
  35. export default resolveUrl;