diff --git a/src/utils/ajax.js b/src/utils/ajax.js index e009c881e..ed4df197b 100644 --- a/src/utils/ajax.js +++ b/src/utils/ajax.js @@ -46,35 +46,39 @@ function configureAjaxAuth( authHeader ) { }, } ); - const originalSend = window.wp.ajax.send; - window.wp.ajax.send = function ( options ) { - const originalBeforeSend = options.beforeSend; + if ( typeof window.wp.ajax.send === 'function' ) { + const originalSend = window.wp.ajax.send; + window.wp.ajax.send = function ( options ) { + const originalBeforeSend = options.beforeSend; - options.beforeSend = function ( xhr ) { - xhr.setRequestHeader( 'Authorization', authHeader ); + options.beforeSend = function ( xhr ) { + xhr.setRequestHeader( 'Authorization', authHeader ); - if ( typeof originalBeforeSend === 'function' ) { - originalBeforeSend( xhr ); - } + if ( typeof originalBeforeSend === 'function' ) { + originalBeforeSend( xhr ); + } + }; + + return originalSend.call( this, options ); }; + } - return originalSend.call( this, options ); - }; + if ( typeof window.wp.ajax.post === 'function' ) { + const originalPost = window.wp.ajax.post; + window.wp.ajax.post = function ( options ) { + const originalBeforeSend = options.beforeSend; - const originalPost = window.wp.ajax.post; - window.wp.ajax.post = function ( options ) { - const originalBeforeSend = options.beforeSend; + options.beforeSend = function ( xhr ) { + xhr.setRequestHeader( 'Authorization', authHeader ); - options.beforeSend = function ( xhr ) { - xhr.setRequestHeader( 'Authorization', authHeader ); + if ( typeof originalBeforeSend === 'function' ) { + originalBeforeSend( xhr ); + } + }; - if ( typeof originalBeforeSend === 'function' ) { - originalBeforeSend( xhr ); - } + return originalPost.call( this, options ); }; - - return originalPost.call( this, options ); - }; + } debug( 'AJAX auth configured' ); } diff --git a/src/utils/ajax.test.js b/src/utils/ajax.test.js index a9f988d58..28cf84cd4 100644 --- a/src/utils/ajax.test.js +++ b/src/utils/ajax.test.js @@ -402,6 +402,9 @@ describe( 'configureAjax', () => { expect( () => configureAjax() ).not.toThrow(); + // Should not wrap send (it doesn't exist) + expect( global.window.wp.ajax.send ).toBeUndefined(); + // Should still wrap post expect( global.window.wp.ajax.post ).not.toBe( originalWpAjaxPost ); } ); @@ -421,6 +424,9 @@ describe( 'configureAjax', () => { expect( () => configureAjax() ).not.toThrow(); + // Should not wrap post (it doesn't exist) + expect( global.window.wp.ajax.post ).toBeUndefined(); + // Should still wrap send expect( global.window.wp.ajax.send ).not.toBe( originalWpAjaxSend ); } );