url.js 1.24 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define([], function () {
    'use strict';

    return {

        /**
         * Redirects to the url if it is considered safe
         *
         * @param {String} path - url to be redirected to
         */
        redirect: function (path) {
            path = this.sanitize(path);

            if (this.validate(path)) {
                window.location.href = path;
            }
        },

        /**
         * Validates url
         *
         * @param {Object} path - url to be validated
         * @returns {Boolean}
         */
        validate: function (path) {
            var hostname = window.location.hostname;

            if (path.indexOf(hostname) === -1 ||
                path.indexOf('javascript:') !== -1 ||
                path.indexOf('vbscript:') !== -1) {
                return false;
            }

            return true;
        },

        /**
         * Sanitize url, replacing disallowed chars
         *
         * @param {String} path - url to be normalized
         * @returns {String}
         */
        sanitize: function (path) {
            return path.replace('[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]', '');
        }
    };
});