| 797 | |
| 798 | this.addHistory(); |
| 799 | }, |
| 800 | |
| 801 | /** |
| 802 | * Given a URL query string, return the query vars contained within it |
| 803 | * |
| 804 | * @param {String} queryString |
| 805 | * @returns {Object} |
| 806 | */ |
| 807 | parseQueryVars: function ( queryString ) { |
| 808 | var queryVars = {}; |
| 809 | if ( queryString ) { |
| 810 | $.each( queryString.split( '&' ), function () { |
| 811 | var key, value, pair; |
| 812 | pair = this.split( '=', 2 ); |
| 813 | key = decodeURIComponent( pair[0] ); |
| 814 | value = pair[1] ? decodeURIComponent( pair[1] ) : null; |
| 815 | queryVars[ key ] = value; |
| 816 | } ); |
| 817 | } |
| 818 | return queryVars; |
| 819 | }, |
| 820 | |
| 821 | /** |
| 822 | * Add support for history for navigation in Customize preview |
| 823 | */ |
| 824 | addHistory: function () { |
| 825 | var self, previousUrl; |
| 826 | if ( ! history.pushState ) { |
| 827 | return; |
| 828 | } |
| 829 | self = this; |
| 830 | |
| 831 | // Push state |
| 832 | this.bind( 'url', function ( url ) { |
| 833 | var state, parentLocation, queryVars; |
| 834 | if ( previousUrl === url ) { |
| 835 | return; |
| 836 | } |
| 837 | previousUrl = url; |
| 838 | |
| 839 | state = { customizePreviewUrl: url }; |
| 840 | parentLocation = location.pathname; |
| 841 | queryVars = self.parseQueryVars( location.search.substr( 1 ) ); |
| 842 | queryVars.url = url; |
| 843 | parentLocation += '?' + $.param( queryVars ); |
| 844 | parentLocation += location.hash; |
| 845 | history.pushState( state, '', parentLocation ); |
| 846 | |
| 847 | $( '.back.button:first' ).prop( 'href', url ); |
| 848 | } ); |
| 849 | |
| 850 | // Pop state |
| 851 | $( window ).on( 'popstate', function ( e ) { |
| 852 | var state, url, queryVars; |
| 853 | state = e.originalEvent.state; |
| 854 | queryVars = self.parseQueryVars( location.search.substr( 1 ) ); |
| 855 | if ( state && state.customizePreviewUrl ) { |
| 856 | url = state.customizePreviewUrl; |
| 857 | } else if ( queryVars.url ) { |
| 858 | url = queryVars.url; |
| 859 | } else { |
| 860 | url = api.settings.url.home; |
| 861 | } |
| 862 | self.previewUrl( url ); |
| 863 | |
| 864 | $( '.back.button:first' ).prop( 'href', url ); |
| 865 | } ); |
| 866 | |