@@ -28,6 +28,11 @@ class FileCacher extends AbstractCacher
2828 */
2929 private $ shouldOutputJs = false ;
3030
31+ /**
32+ * @var string
33+ */
34+ private $ csrfTokenJs ;
35+
3136 /**
3237 * @var string
3338 */
@@ -230,16 +235,59 @@ private function isLongQueryStringPath($path)
230235 return Str::contains ($ path , '_lqs_ ' );
231236 }
232237
238+ public function setCsrfTokenJs (string $ js )
239+ {
240+ $ this ->csrfTokenJs = $ js ;
241+ }
242+
233243 public function setNocacheJs (string $ js )
234244 {
235245 $ this ->nocacheJs = $ js ;
236246 }
237247
238- public function getNocacheJs (): string
248+ public function getCsrfTokenJs (): string
239249 {
240250 $ csrfPlaceholder = CsrfTokenReplacer::REPLACEMENT ;
241251
242252 $ default = <<<EOT
253+ (function() {
254+ fetch('/!/csrf', {
255+ method: 'POST',
256+ headers: { 'Content-Type': 'application/json' },
257+ })
258+ .then((response) => response.json())
259+ .then((data) => {
260+ for (const input of document.querySelectorAll('input[value=" $ csrfPlaceholder"]')) {
261+ input.value = data.csrf;
262+ }
263+
264+ for (const meta of document.querySelectorAll('meta[content=" $ csrfPlaceholder"]')) {
265+ meta.content = data.csrf;
266+ }
267+
268+ for (const input of document.querySelectorAll('script[data-csrf=" $ csrfPlaceholder"]')) {
269+ input.setAttribute('data-csrf', data.csrf);
270+ }
271+
272+ if (window.hasOwnProperty('livewire_token')) {
273+ window.livewire_token = data.csrf
274+ }
275+
276+ if (window.hasOwnProperty('livewireScriptConfig')) {
277+ window.livewireScriptConfig.csrf = data.csrf
278+ }
279+
280+ document.dispatchEvent(new CustomEvent('statamic:csrf.replaced', { detail: data }));
281+ });
282+ })();
283+ EOT ;
284+
285+ return $ this ->csrfTokenJs ?? $ default ;
286+ }
287+
288+ public function getNocacheJs (): string
289+ {
290+ $ default = <<<'EOT'
243291(function() {
244292 function createMap() {
245293 var map = {};
@@ -270,26 +318,6 @@ function createMap() {
270318 if (map[key]) map[key].outerHTML = regions[key];
271319 }
272320
273- for (const input of document.querySelectorAll('input[value=" $ csrfPlaceholder"]')) {
274- input.value = data.csrf;
275- }
276-
277- for (const meta of document.querySelectorAll('meta[content=" $ csrfPlaceholder"]')) {
278- meta.content = data.csrf;
279- }
280-
281- for (const input of document.querySelectorAll('script[data-csrf=" $ csrfPlaceholder"]')) {
282- input.setAttribute('data-csrf', data.csrf);
283- }
284-
285- if (window.hasOwnProperty('livewire_token')) {
286- window.livewire_token = data.csrf
287- }
288-
289- if (window.hasOwnProperty('livewireScriptConfig')) {
290- window.livewireScriptConfig.csrf = data.csrf
291- }
292-
293321 document.dispatchEvent(new CustomEvent('statamic:nocache.replaced', { detail: data }));
294322 });
295323})();
0 commit comments