Skip to content

Commit b41fbb9

Browse files
committed
Persist URL fragment during client-side mobile redirection and guard against infinite redirect (#5775)
1 parent 950396c commit b41fbb9

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

assets/src/mobile-redirection.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,27 @@
5353
return;
5454
}
5555

56-
const url = new URL( location.href );
56+
const locationUrlObject = new URL( location.href );
57+
const amphtmlUrlObject = new URL( ampUrl );
5758

58-
if ( url.searchParams.has( noampQueryVarName ) && noampQueryVarValue === url.searchParams.get( noampQueryVarName ) ) {
59+
// Persist the URL fragment when redirecting to the AMP version. This is needed because the server-generated amphtml
60+
// link has no awareness of the client-side URL target.
61+
amphtmlUrlObject.hash = locationUrlObject.hash;
62+
63+
if ( locationUrlObject.searchParams.has( noampQueryVarName ) && noampQueryVarValue === locationUrlObject.searchParams.get( noampQueryVarName ) ) {
5964
// If the noamp query param is present, remember that redirection should be disabled.
6065
sessionStorage.setItem( disabledStorageKey, '1' );
61-
} else {
66+
} else if ( amphtmlUrlObject.href !== locationUrlObject.href ) {
6267
// Otherwise, since JS is running then we know it's not an AMP page and we need to redirect to the AMP version.
68+
// Nevertheless, the `url.href !== location.href` condition was added for the edge case where a caching plugin
69+
// is erroneously serving a cached non-AMP page at the AMP URL, so the condition prevents an infinite redirect
70+
// from ensuing. See <https://github.com/ampproject/amp-wp/issues/5767>.
6371
window.stop(); // Stop loading the page! This should cancel all loading resources.
6472

6573
// Replace the current page with the AMP version.
66-
location.replace( ampUrl );
74+
location.replace( amphtmlUrlObject.href );
6775
}
6876
}(
69-
// Note: The argument here is replaced with JSON in PHP by \AmpProject\AmpWP\MobileRedirection::add_mobile_redirect_script().
77+
// Note: The argument here is replaced with a JSON object literal in PHP by \AmpProject\AmpWP\MobileRedirection::add_mobile_redirect_script().
7078
AMP_MOBILE_REDIRECTION,
7179
) );

0 commit comments

Comments
 (0)