2 * Script run inside a Customizer preview frame.
4 (function( exports, $ ){
5 var api = wp.customize,
7 currentHistoryState = {};
10 * Capture the state that is passed into history.replaceState() and history.pushState()
11 * and also which is returned in the popstate event so that when the changeset_uuid
12 * gets updated when transitioning to a new changeset there the current state will
13 * be supplied in the call to history.replaceState().
15 ( function( history ) {
16 var injectUrlWithState;
18 if ( ! history.replaceState ) {
23 * Amend the supplied URL with the customized state.
28 * @param {string} url URL.
29 * @returns {string} URL with customized state.
31 injectUrlWithState = function( url ) {
32 var urlParser, oldQueryParams, newQueryParams;
33 urlParser = document.createElement( 'a' );
35 oldQueryParams = api.utils.parseQueryString( location.search.substr( 1 ) );
36 newQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
38 newQueryParams.customize_changeset_uuid = oldQueryParams.customize_changeset_uuid;
39 if ( oldQueryParams.customize_theme ) {
40 newQueryParams.customize_theme = oldQueryParams.customize_theme;
42 if ( oldQueryParams.customize_messenger_channel ) {
43 newQueryParams.customize_messenger_channel = oldQueryParams.customize_messenger_channel;
45 urlParser.search = $.param( newQueryParams );
46 return urlParser.href;
49 history.replaceState = ( function( nativeReplaceState ) {
50 return function historyReplaceState( data, title, url ) {
51 currentHistoryState = data;
52 return nativeReplaceState.call( history, data, title, injectUrlWithState( url ) );
54 } )( history.replaceState );
56 history.pushState = ( function( nativePushState ) {
57 return function historyPushState( data, title, url ) {
58 currentHistoryState = data;
59 return nativePushState.call( history, data, title, injectUrlWithState( url ) );
61 } )( history.pushState );
63 window.addEventListener( 'popstate', function( event ) {
64 currentHistoryState = event.state;
70 * Returns a debounced version of the function.
72 * @todo Require Underscore.js for this file and retire this.
74 debounce = function( fn, delay, context ) {
79 context = context || this;
81 clearTimeout( timeout );
82 timeout = setTimeout( function() {
84 fn.apply( context, args );
91 * @augments wp.customize.Messenger
92 * @augments wp.customize.Class
93 * @mixes wp.customize.Events
95 api.Preview = api.Messenger.extend({
97 * @param {object} params - Parameters to configure the messenger.
98 * @param {object} options - Extend any instance parameter or method with this object.
100 initialize: function( params, options ) {
101 var preview = this, urlParser = document.createElement( 'a' );
103 api.Messenger.prototype.initialize.call( preview, params, options );
105 urlParser.href = preview.origin();
106 preview.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) );
108 preview.body = $( document.body );
109 preview.window = $( window );
111 if ( api.settings.channel ) {
113 // If in an iframe, then intercept the link clicks and form submissions.
114 preview.body.on( 'click.preview', 'a', function( event ) {
115 preview.handleLinkClick( event );
117 preview.body.on( 'submit.preview', 'form', function( event ) {
118 preview.handleFormSubmit( event );
121 preview.window.on( 'scroll.preview', debounce( function() {
122 preview.send( 'scroll', preview.window.scrollTop() );
125 preview.bind( 'scroll', function( distance ) {
126 preview.window.scrollTop( distance );
132 * Handle link clicks in preview.
137 * @param {jQuery.Event} event Event.
139 handleLinkClick: function( event ) {
140 var preview = this, link, isInternalJumpLink;
141 link = $( event.target );
143 // No-op if the anchor is not a link.
144 if ( _.isUndefined( link.attr( 'href' ) ) ) {
148 isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
150 // Allow internal jump links to behave normally without preventing default.
151 if ( isInternalJumpLink ) {
155 // If the link is not previewable, prevent the browser from navigating to it.
156 if ( ! api.isLinkPreviewable( link[0] ) ) {
157 wp.a11y.speak( api.settings.l10n.linkUnpreviewable );
158 event.preventDefault();
162 // Prevent initiating navigating from click and instead rely on sending url message to pane.
163 event.preventDefault();
166 * Note the shift key is checked so shift+click on widgets or
167 * nav menu items can just result on focusing on the corresponding
168 * control instead of also navigating to the URL linked to.
170 if ( event.shiftKey ) {
174 // Note: It's not relevant to send scroll because sending url message will have the same effect.
175 preview.send( 'url', link.prop( 'href' ) );
179 * Handle form submit.
184 * @param {jQuery.Event} event Event.
186 handleFormSubmit: function( event ) {
187 var preview = this, urlParser, form;
188 urlParser = document.createElement( 'a' );
189 form = $( event.target );
190 urlParser.href = form.prop( 'action' );
192 // If the link is not previewable, prevent the browser from navigating to it.
193 if ( 'GET' !== form.prop( 'method' ).toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
194 wp.a11y.speak( api.settings.l10n.formUnpreviewable );
195 event.preventDefault();
200 * If the default wasn't prevented already (in which case the form
201 * submission is already being handled by JS), and if it has a GET
202 * request method, then take the serialized form data and add it as
203 * a query string to the action URL and send this in a url message
204 * to the customizer pane so that it will be loaded. If the form's
205 * action points to a non-previewable URL, the customizer pane's
206 * previewUrl setter will reject it so that the form submission is
207 * a no-op, which is the same behavior as when clicking a link to an
208 * external site in the preview.
210 if ( ! event.isDefaultPrevented() ) {
211 if ( urlParser.search.length > 1 ) {
212 urlParser.search += '&';
214 urlParser.search += form.serialize();
215 preview.send( 'url', urlParser.href );
218 // Prevent default since navigation should be done via sending url message or via JS submit handler.
219 event.preventDefault();
224 * Inject the changeset UUID into links in the document.
232 api.addLinkPreviewing = function addLinkPreviewing() {
233 var linkSelectors = 'a[href], area';
235 // Inject links into initial document.
236 $( document.body ).find( linkSelectors ).each( function() {
237 api.prepareLinkPreview( this );
240 // Inject links for new elements added to the page.
241 if ( 'undefined' !== typeof MutationObserver ) {
242 api.mutationObserver = new MutationObserver( function( mutations ) {
243 _.each( mutations, function( mutation ) {
244 $( mutation.target ).find( linkSelectors ).each( function() {
245 api.prepareLinkPreview( this );
249 api.mutationObserver.observe( document.documentElement, {
255 // If mutation observers aren't available, fallback to just-in-time injection.
256 $( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
257 api.prepareLinkPreview( this );
263 * Should the supplied link is previewable.
268 * @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
269 * @param {string} element.search Query string.
270 * @param {string} element.pathname Path.
271 * @param {string} element.host Host.
272 * @param {object} [options]
273 * @param {object} [options.allowAdminAjax=false] Allow admin-ajax.php requests.
274 * @returns {boolean} Is appropriate for changeset link.
276 api.isLinkPreviewable = function isLinkPreviewable( element, options ) {
277 var matchesAllowedUrl, parsedAllowedUrl, args;
279 args = _.extend( {}, { allowAdminAjax: false }, options || {} );
281 if ( 'javascript:' === element.protocol ) { // jshint ignore:line
285 // Only web URLs can be previewed.
286 if ( 'https:' !== element.protocol && 'http:' !== element.protocol ) {
290 parsedAllowedUrl = document.createElement( 'a' );
291 matchesAllowedUrl = ! _.isUndefined( _.find( api.settings.url.allowed, function( allowedUrl ) {
292 parsedAllowedUrl.href = allowedUrl;
293 return parsedAllowedUrl.protocol === element.protocol && parsedAllowedUrl.host === element.host && 0 === element.pathname.indexOf( parsedAllowedUrl.pathname.replace( /\/$/, '' ) );
295 if ( ! matchesAllowedUrl ) {
299 // Skip wp login and signup pages.
300 if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
304 // Allow links to admin ajax as faux frontend URLs.
305 if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
306 return args.allowAdminAjax;
309 // Disallow links to admin, includes, and content.
310 if ( /\/wp-(admin|includes|content)(\/|$)/.test( element.pathname ) ) {
318 * Inject the customize_changeset_uuid query param into links on the frontend.
323 * @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
324 * @param {string} element.search Query string.
325 * @param {string} element.host Host.
326 * @param {string} element.protocol Protocol.
329 api.prepareLinkPreview = function prepareLinkPreview( element ) {
332 // Skip links in admin bar.
333 if ( $( element ).closest( '#wpadminbar' ).length ) {
337 // Ignore links with href="#" or href="#id".
338 if ( '#' === $( element ).attr( 'href' ).substr( 0, 1 ) ) {
342 // Make sure links in preview use HTTPS if parent frame uses HTTPS.
343 if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === element.protocol && -1 !== api.settings.url.allowedHosts.indexOf( element.host ) ) {
344 element.protocol = 'https:';
347 if ( ! api.isLinkPreviewable( element ) ) {
349 // Style link as unpreviewable only if previewing in iframe; if previewing on frontend, links will be allowed to work normally.
350 if ( api.settings.channel ) {
351 $( element ).addClass( 'customize-unpreviewable' );
355 $( element ).removeClass( 'customize-unpreviewable' );
357 queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
358 queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
359 if ( ! api.settings.theme.active ) {
360 queryParams.customize_theme = api.settings.theme.stylesheet;
362 if ( api.settings.channel ) {
363 queryParams.customize_messenger_channel = api.settings.channel;
365 element.search = $.param( queryParams );
367 // Prevent links from breaking out of preview iframe.
368 if ( api.settings.channel ) {
369 element.target = '_self';
374 * Inject the changeset UUID into Ajax requests.
381 api.addRequestPreviewing = function addRequestPreviewing() {
384 * Rewrite Ajax requests to inject customizer state.
386 * @param {object} options Options.
387 * @param {string} options.type Type.
388 * @param {string} options.url URL.
389 * @param {object} originalOptions Original options.
390 * @param {XMLHttpRequest} xhr XHR.
393 var prefilterAjax = function( options, originalOptions, xhr ) {
394 var urlParser, queryParams, requestMethod, dirtyValues = {};
395 urlParser = document.createElement( 'a' );
396 urlParser.href = options.url;
398 // Abort if the request is not for this site.
399 if ( ! api.isLinkPreviewable( urlParser, { allowAdminAjax: true } ) ) {
402 queryParams = api.utils.parseQueryString( urlParser.search.substring( 1 ) );
404 // Note that _dirty flag will be cleared with changeset updates.
405 api.each( function( setting ) {
406 if ( setting._dirty ) {
407 dirtyValues[ setting.id ] = setting.get();
411 if ( ! _.isEmpty( dirtyValues ) ) {
412 requestMethod = options.type.toUpperCase();
414 // Override underlying request method to ensure unsaved changes to changeset can be included (force Backbone.emulateHTTP).
415 if ( 'POST' !== requestMethod ) {
416 xhr.setRequestHeader( 'X-HTTP-Method-Override', requestMethod );
417 queryParams._method = requestMethod;
418 options.type = 'POST';
421 // Amend the post data with the customized values.
422 if ( options.data ) {
427 options.data += $.param( {
428 customized: JSON.stringify( dirtyValues )
432 // Include customized state query params in URL.
433 queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
434 if ( ! api.settings.theme.active ) {
435 queryParams.customize_theme = api.settings.theme.stylesheet;
437 urlParser.search = $.param( queryParams );
438 options.url = urlParser.href;
441 $.ajaxPrefilter( prefilterAjax );
445 * Inject changeset UUID into forms, allowing preview to persist through submissions.
452 api.addFormPreviewing = function addFormPreviewing() {
454 // Inject inputs for forms in initial document.
455 $( document.body ).find( 'form' ).each( function() {
456 api.prepareFormPreview( this );
459 // Inject inputs for new forms added to the page.
460 if ( 'undefined' !== typeof MutationObserver ) {
461 api.mutationObserver = new MutationObserver( function( mutations ) {
462 _.each( mutations, function( mutation ) {
463 $( mutation.target ).find( 'form' ).each( function() {
464 api.prepareFormPreview( this );
468 api.mutationObserver.observe( document.documentElement, {
476 * Inject changeset into form inputs.
481 * @param {HTMLFormElement} form Form.
484 api.prepareFormPreview = function prepareFormPreview( form ) {
485 var urlParser, stateParams = {};
487 if ( ! form.action ) {
488 form.action = location.href;
491 urlParser = document.createElement( 'a' );
492 urlParser.href = form.action;
494 // Make sure forms in preview use HTTPS if parent frame uses HTTPS.
495 if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === urlParser.protocol && -1 !== api.settings.url.allowedHosts.indexOf( urlParser.host ) ) {
496 urlParser.protocol = 'https:';
497 form.action = urlParser.href;
500 if ( 'GET' !== form.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
502 // Style form as unpreviewable only if previewing in iframe; if previewing on frontend, all forms will be allowed to work normally.
503 if ( api.settings.channel ) {
504 $( form ).addClass( 'customize-unpreviewable' );
508 $( form ).removeClass( 'customize-unpreviewable' );
510 stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
511 if ( ! api.settings.theme.active ) {
512 stateParams.customize_theme = api.settings.theme.stylesheet;
514 if ( api.settings.channel ) {
515 stateParams.customize_messenger_channel = api.settings.channel;
518 _.each( stateParams, function( value, name ) {
519 var input = $( form ).find( 'input[name="' + name + '"]' );
520 if ( input.length ) {
523 $( form ).prepend( $( '<input>', {
531 // Prevent links from breaking out of preview iframe.
532 if ( api.settings.channel ) {
533 form.target = '_self';
538 * Watch current URL and send keep-alive (heartbeat) messages to the parent.
540 * Keep the customizer pane notified that the preview is still alive
541 * and that the user hasn't navigated to a non-customized URL.
546 api.keepAliveCurrentUrl = ( function() {
547 var previousPathName = location.pathname,
548 previousQueryString = location.search.substr( 1 ),
549 previousQueryParams = null,
550 stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel' ];
552 return function keepAliveCurrentUrl() {
553 var urlParser, currentQueryParams;
555 // Short-circuit with keep-alive if previous URL is identical (as is normal case).
556 if ( previousQueryString === location.search.substr( 1 ) && previousPathName === location.pathname ) {
557 api.preview.send( 'keep-alive' );
561 urlParser = document.createElement( 'a' );
562 if ( null === previousQueryParams ) {
563 urlParser.search = previousQueryString;
564 previousQueryParams = api.utils.parseQueryString( previousQueryString );
565 _.each( stateQueryParams, function( name ) {
566 delete previousQueryParams[ name ];
570 // Determine if current URL minus customized state params and URL hash.
571 urlParser.href = location.href;
572 currentQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
573 _.each( stateQueryParams, function( name ) {
574 delete currentQueryParams[ name ];
577 if ( previousPathName !== location.pathname || ! _.isEqual( previousQueryParams, currentQueryParams ) ) {
578 urlParser.search = $.param( currentQueryParams );
580 api.settings.url.self = urlParser.href;
581 api.preview.send( 'ready', {
582 currentUrl: api.settings.url.self,
583 activePanels: api.settings.activePanels,
584 activeSections: api.settings.activeSections,
585 activeControls: api.settings.activeControls,
586 settingValidities: api.settings.settingValidities
589 api.preview.send( 'keep-alive' );
591 previousQueryParams = currentQueryParams;
592 previousQueryString = location.search.substr( 1 );
593 previousPathName = location.pathname;
597 api.settingPreviewHandlers = {
600 * Preview changes to custom logo.
602 * @param {number} attachmentId Attachment ID for custom logo.
605 custom_logo: function( attachmentId ) {
606 $( 'body' ).toggleClass( 'wp-custom-logo', !! attachmentId );
610 * Preview changes to custom css.
612 * @param {string} value Custom CSS..
615 custom_css: function( value ) {
616 $( '#wp-custom-css' ).text( value );
620 * Preview changes to any of the background settings.
624 background: function() {
625 var css = '', settings = {};
627 _.each( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
628 settings[ prop ] = api( 'background_' + prop );
632 * The body will support custom backgrounds if either the color or image are set.
634 * See get_body_class() in /wp-includes/post-template.php
636 $( document.body ).toggleClass( 'custom-background', !! ( settings.color() || settings.image() ) );
638 if ( settings.color() ) {
639 css += 'background-color: ' + settings.color() + ';';
642 if ( settings.image() ) {
643 css += 'background-image: url("' + settings.image() + '");';
644 css += 'background-size: ' + settings.size() + ';';
645 css += 'background-position: ' + settings.position_x() + ' ' + settings.position_y() + ';';
646 css += 'background-repeat: ' + settings.repeat() + ';';
647 css += 'background-attachment: ' + settings.attachment() + ';';
650 $( '#custom-background-css' ).text( 'body.custom-background { ' + css + ' }' );
657 api.settings = window._wpCustomizeSettings;
658 if ( ! api.settings ) {
662 api.preview = new api.Preview({
663 url: window.location.href,
664 channel: api.settings.channel
667 api.addLinkPreviewing();
668 api.addRequestPreviewing();
669 api.addFormPreviewing();
672 * Create/update a setting value.
674 * @param {string} id - Setting ID.
675 * @param {*} value - Setting value.
676 * @param {boolean} [createDirty] - Whether to create a setting as dirty. Defaults to false.
678 setValue = function( id, value, createDirty ) {
679 var setting = api( id );
681 setting.set( value );
683 createDirty = createDirty || false;
684 setting = api.create( id, value, {
688 // Mark dynamically-created settings as dirty so they will get posted.
690 setting._dirty = true;
695 api.preview.bind( 'settings', function( values ) {
696 $.each( values, setValue );
699 api.preview.trigger( 'settings', api.settings.values );
701 $.each( api.settings._dirty, function( i, id ) {
702 var setting = api( id );
704 setting._dirty = true;
708 api.preview.bind( 'setting', function( args ) {
709 var createDirty = true;
710 setValue.apply( null, args.concat( createDirty ) );
713 api.preview.bind( 'sync', function( events ) {
716 * Delete any settings that already exist locally which haven't been
717 * modified in the controls while the preview was loading. This prevents
718 * situations where the JS value being synced from the pane may differ
719 * from the PHP-sanitized JS value in the preview which causes the
720 * non-sanitized JS value to clobber the PHP-sanitized value. This
721 * is particularly important for selective refresh partials that
722 * have a fallback refresh behavior since infinite refreshing would
725 if ( events.settings && events['settings-modified-while-loading'] ) {
726 _.each( _.keys( events.settings ), function( syncedSettingId ) {
727 if ( api.has( syncedSettingId ) && ! events['settings-modified-while-loading'][ syncedSettingId ] ) {
728 delete events.settings[ syncedSettingId ];
733 $.each( events, function( event, args ) {
734 api.preview.trigger( event, args );
736 api.preview.send( 'synced' );
739 api.preview.bind( 'active', function() {
740 api.preview.send( 'nonce', api.settings.nonce );
742 api.preview.send( 'documentTitle', document.title );
744 // Send scroll in case of loading via non-refresh.
745 api.preview.send( 'scroll', $( window ).scrollTop() );
748 api.preview.bind( 'saved', function( response ) {
750 if ( response.next_changeset_uuid ) {
751 api.settings.changeset.uuid = response.next_changeset_uuid;
753 // Update UUIDs in links and forms.
754 $( document.body ).find( 'a[href], area' ).each( function() {
755 api.prepareLinkPreview( this );
757 $( document.body ).find( 'form' ).each( function() {
758 api.prepareFormPreview( this );
762 * Replace the UUID in the URL. Note that the wrapped history.replaceState()
763 * will handle injecting the current api.settings.changeset.uuid into the URL,
764 * so this is merely to trigger that logic.
766 if ( history.replaceState ) {
767 history.replaceState( currentHistoryState, '', location.href );
771 api.trigger( 'saved', response );
775 * Clear dirty flag for settings when saved to changeset so that they
776 * won't be needlessly included in selective refresh or ajax requests.
778 api.preview.bind( 'changeset-saved', function( data ) {
779 _.each( data.saved_changeset_values, function( value, settingId ) {
780 var setting = api( settingId );
781 if ( setting && _.isEqual( setting.get(), value ) ) {
782 setting._dirty = false;
787 api.preview.bind( 'nonce-refresh', function( nonce ) {
788 $.extend( api.settings.nonce, nonce );
792 * Send a message to the parent customize frame with a list of which
793 * containers and controls are active.
795 api.preview.send( 'ready', {
796 currentUrl: api.settings.url.self,
797 activePanels: api.settings.activePanels,
798 activeSections: api.settings.activeSections,
799 activeControls: api.settings.activeControls,
800 settingValidities: api.settings.settingValidities
803 // Send ready when URL changes via JS.
804 setInterval( api.keepAliveCurrentUrl, api.settings.timeouts.keepAliveSend );
806 // Display a loading indicator when preview is reloading, and remove on failure.
807 api.preview.bind( 'loading-initiated', function () {
808 $( 'body' ).addClass( 'wp-customizer-unloading' );
810 api.preview.bind( 'loading-failed', function () {
811 $( 'body' ).removeClass( 'wp-customizer-unloading' );
814 /* Custom Backgrounds */
815 bg = $.map( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
816 return 'background_' + prop;
819 api.when.apply( api, bg ).done( function() {
820 $.each( arguments, function() {
821 this.bind( api.settingPreviewHandlers.background );
828 * Toggle the wp-custom-logo body class when a logo is added or removed.
832 api( 'custom_logo', function ( setting ) {
833 api.settingPreviewHandlers.custom_logo.call( setting, setting.get() );
834 setting.bind( api.settingPreviewHandlers.custom_logo );
837 api( 'custom_css[' + api.settings.theme.stylesheet + ']', function( setting ) {
838 setting.bind( api.settingPreviewHandlers.custom_css );
841 api.trigger( 'preview-ready' );