url.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. define([], function () {
  6. 'use strict';
  7. return {
  8. /**
  9. * Redirects to the url if it is considered safe
  10. *
  11. * @param {String} path - url to be redirected to
  12. */
  13. redirect: function (path) {
  14. path = this.sanitize(path);
  15. if (this.validate(path)) {
  16. window.location.href = path;
  17. }
  18. },
  19. /**
  20. * Validates url
  21. *
  22. * @param {Object} path - url to be validated
  23. * @returns {Boolean}
  24. */
  25. validate: function (path) {
  26. var hostname = window.location.hostname;
  27. if (path.indexOf(hostname) === -1 ||
  28. path.indexOf('javascript:') !== -1 ||
  29. path.indexOf('vbscript:') !== -1) {
  30. return false;
  31. }
  32. return true;
  33. },
  34. /**
  35. * Sanitize url, replacing disallowed chars
  36. *
  37. * @param {String} path - url to be normalized
  38. * @returns {String}
  39. */
  40. sanitize: function (path) {
  41. return path.replace('[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]', '');
  42. }
  43. };
  44. });