|
| 1 | +/** |
| 2 | + * Internal dependencies |
| 3 | + */ |
| 4 | +import { getGBKit } from './bridge'; |
| 5 | +import { warn, debug } from './logger'; |
| 6 | + |
| 7 | +/** |
| 8 | + * GutenbergKit lacks authentication cookies required for AJAX requests. |
| 9 | + * This configures a root URL and authentication header for AJAX requests. |
| 10 | + * |
| 11 | + * @return {void} |
| 12 | + */ |
| 13 | +export function initializeAjax() { |
| 14 | + window.wp = window.wp || {}; |
| 15 | + window.wp.ajax = window.wp.ajax || {}; |
| 16 | + window.wp.ajax.settings = window.wp.ajax.settings || {}; |
| 17 | + |
| 18 | + const { siteURL, authHeader } = getGBKit(); |
| 19 | + configureAjaxUrl( siteURL ); |
| 20 | + configureAjaxAuth( authHeader ); |
| 21 | +} |
| 22 | + |
| 23 | +function configureAjaxUrl( siteURL ) { |
| 24 | + if ( ! siteURL ) { |
| 25 | + warn( 'Unable to configure AJAX URL without siteURL' ); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + window.wp.ajax.settings.url = `${ siteURL }/wp-admin/admin-ajax.php`; |
| 30 | + |
| 31 | + debug( 'AJAX URL configured' ); |
| 32 | +} |
| 33 | + |
| 34 | +function configureAjaxAuth( authHeader ) { |
| 35 | + if ( ! authHeader ) { |
| 36 | + warn( 'Unable to configure AJAX auth without authHeader' ); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + window.jQuery?.ajaxSetup( { |
| 41 | + headers: { |
| 42 | + Authorization: authHeader, |
| 43 | + }, |
| 44 | + } ); |
| 45 | + |
| 46 | + const originalSend = window.wp.ajax.send; |
| 47 | + window.wp.ajax.send = function ( options ) { |
| 48 | + const originalBeforeSend = options.beforeSend; |
| 49 | + |
| 50 | + options.beforeSend = function ( xhr ) { |
| 51 | + xhr.setRequestHeader( 'Authorization', authHeader ); |
| 52 | + |
| 53 | + if ( typeof originalBeforeSend === 'function' ) { |
| 54 | + originalBeforeSend( xhr ); |
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + return originalSend.call( this, options ); |
| 59 | + }; |
| 60 | + |
| 61 | + const originalPost = window.wp.ajax.post; |
| 62 | + window.wp.ajax.post = function ( options ) { |
| 63 | + const originalBeforeSend = options.beforeSend; |
| 64 | + |
| 65 | + options.beforeSend = function ( xhr ) { |
| 66 | + xhr.setRequestHeader( 'Authorization', authHeader ); |
| 67 | + |
| 68 | + if ( typeof originalBeforeSend === 'function' ) { |
| 69 | + originalBeforeSend( xhr ); |
| 70 | + } |
| 71 | + }; |
| 72 | + |
| 73 | + return originalPost.call( this, options ); |
| 74 | + }; |
| 75 | + |
| 76 | + debug( 'AJAX auth configured' ); |
| 77 | +} |
0 commit comments