isURLSameOrigin.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. import utils from './../utils.js';
  3. import platform from '../platform/index.js';
  4. export default platform.hasStandardBrowserEnv ?
  5. // Standard browser envs have full support of the APIs needed to test
  6. // whether the request URL is of the same origin as current location.
  7. (function standardBrowserEnv() {
  8. const msie = /(msie|trident)/i.test(navigator.userAgent);
  9. const urlParsingNode = document.createElement('a');
  10. let originURL;
  11. /**
  12. * Parse a URL to discover its components
  13. *
  14. * @param {String} url The URL to be parsed
  15. * @returns {Object}
  16. */
  17. function resolveURL(url) {
  18. let href = url;
  19. if (msie) {
  20. // IE needs attribute set twice to normalize properties
  21. urlParsingNode.setAttribute('href', href);
  22. href = urlParsingNode.href;
  23. }
  24. urlParsingNode.setAttribute('href', href);
  25. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  26. return {
  27. href: urlParsingNode.href,
  28. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  29. host: urlParsingNode.host,
  30. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  31. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  32. hostname: urlParsingNode.hostname,
  33. port: urlParsingNode.port,
  34. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  35. urlParsingNode.pathname :
  36. '/' + urlParsingNode.pathname
  37. };
  38. }
  39. originURL = resolveURL(window.location.href);
  40. /**
  41. * Determine if a URL shares the same origin as the current location
  42. *
  43. * @param {String} requestURL The URL to test
  44. * @returns {boolean} True if URL shares the same origin, otherwise false
  45. */
  46. return function isURLSameOrigin(requestURL) {
  47. const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  48. return (parsed.protocol === originURL.protocol &&
  49. parsed.host === originURL.host);
  50. };
  51. })() :
  52. // Non standard browser envs (web workers, react-native) lack needed support.
  53. (function nonStandardBrowserEnv() {
  54. return function isURLSameOrigin() {
  55. return true;
  56. };
  57. })();