From c133d1220bb02fda8abfcdc155e085a1c415a930 Mon Sep 17 00:00:00 2001 From: Andrew Duthie Date: Wed, 23 Jan 2019 16:46:39 -0500 Subject: [PATCH] Framework: Assign nonce on heartbeat tick via inline script --- lib/client-assets.php | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/client-assets.php b/lib/client-assets.php index 630a50434c72f..7ac5d0700903c 100644 --- a/lib/client-assets.php +++ b/lib/client-assets.php @@ -185,10 +185,29 @@ function gutenberg_register_scripts_and_styles() { gutenberg_register_packages_scripts(); // Inline scripts. + global $wp_scripts; + $wp_scripts->registered['wp-api-fetch']->deps[] = 'wp-hooks'; wp_add_inline_script( 'wp-api-fetch', sprintf( - 'wp.apiFetch.use( wp.apiFetch.createNonceMiddleware( "%s" ) );', + implode( + "\n", + array( + '( function() {', + ' var nonceMiddleware = wp.apiFetch.createNonceMiddleware( "%s" );', + ' wp.apiFetch.use( nonceMiddleware );', + ' wp.hooks.addAction(', + ' "heartbeat.tick",', + ' "core/api-fetch/create-nonce-middleware",', + ' function( response ) {', + ' if ( response[ "rest_nonce" ] ) {', + ' nonceMiddleware.nonce = response[ "rest_nonce" ];', + ' }', + ' }', + ' )', + '} )()', + ) + ), ( wp_installing() && ! is_multisite() ) ? '' : wp_create_nonce( 'wp_rest' ) ), 'after'