From 77650362565861757541cc21f644bf1767fc3c1b Mon Sep 17 00:00:00 2001 From: Khadreal Date: Mon, 20 Jan 2025 16:39:35 +0100 Subject: [PATCH] PR review modifications --- .../PerformanceHints/Frontend/Processor.php | 9 +++++++-- .../Subscriber/HTML/double_body_tag.html | 17 +++++++++++++++-- .../Subscriber/HTML/output_double_body_tag.html | 17 +++++++++++++++-- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/inc/Engine/Common/PerformanceHints/Frontend/Processor.php b/inc/Engine/Common/PerformanceHints/Frontend/Processor.php index 4056268771..3fb8837dc9 100644 --- a/inc/Engine/Common/PerformanceHints/Frontend/Processor.php +++ b/inc/Engine/Common/PerformanceHints/Frontend/Processor.php @@ -190,9 +190,14 @@ private function inject_beacon( $html, $url, $is_mobile ): string { // Create the script tag. $script_tag = ""; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript + $body_tag = strrpos( $html, '' ); - // Append the script tag just before the closing body tag. - return preg_replace( '/<\/body>/', $inline_script . $script_tag . '', $html, 1 ); + if ( false !== $body_tag ) { + // Append the script tag just before the last closing body tag especially in cases where there's an iframe. + $html = substr_replace( $html, $inline_script . $script_tag . '', $body_tag, 7 ); + } + + return $html; } /** diff --git a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/double_body_tag.html b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/double_body_tag.html index 5ac6a6d823..61d4f9f0f3 100644 --- a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/double_body_tag.html +++ b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/double_body_tag.html @@ -3,7 +3,20 @@ Test - - + diff --git a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_double_body_tag.html b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_double_body_tag.html index a918b25207..44ba1df4c0 100644 --- a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_double_body_tag.html +++ b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_double_body_tag.html @@ -3,7 +3,20 @@ Test + - -