You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.3 KiB

  1. 'use strict';
  2. var utils = require('./../utils');
  3. module.exports = (
  4. utils.isStandardBrowserEnv() ?
  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. var msie = /(msie|trident)/i.test(navigator.userAgent);
  9. var urlParsingNode = document.createElement('a');
  10. var originURL;
  11. /**
  12. * Parse a URL to discover it's components
  13. *
  14. * @param {String} url The URL to be parsed
  15. * @returns {Object}
  16. */
  17. function resolveURL(url) {
  18. var 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. var 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. })()
  58. );