diff --git a/assets/src/mobile-redirection.js b/assets/src/mobile-redirection.js index 63ed99f3860..ba833e45e10 100644 --- a/assets/src/mobile-redirection.js +++ b/assets/src/mobile-redirection.js @@ -53,19 +53,27 @@ return; } - const url = new URL( location.href ); + const locationUrlObject = new URL( location.href ); + const amphtmlUrlObject = new URL( ampUrl ); - if ( url.searchParams.has( noampQueryVarName ) && noampQueryVarValue === url.searchParams.get( noampQueryVarName ) ) { + // Persist the URL fragment when redirecting to the AMP version. This is needed because the server-generated amphtml + // link has no awareness of the client-side URL target. + amphtmlUrlObject.hash = locationUrlObject.hash; + + if ( locationUrlObject.searchParams.has( noampQueryVarName ) && noampQueryVarValue === locationUrlObject.searchParams.get( noampQueryVarName ) ) { // If the noamp query param is present, remember that redirection should be disabled. sessionStorage.setItem( disabledStorageKey, '1' ); - } else { + } else if ( amphtmlUrlObject.href !== locationUrlObject.href ) { // Otherwise, since JS is running then we know it's not an AMP page and we need to redirect to the AMP version. + // Nevertheless, the `url.href !== location.href` condition was added for the edge case where a caching plugin + // is erroneously serving a cached non-AMP page at the AMP URL, so the condition prevents an infinite redirect + // from ensuing. See . window.stop(); // Stop loading the page! This should cancel all loading resources. // Replace the current page with the AMP version. - location.replace( ampUrl ); + location.replace( amphtmlUrlObject.href ); } }( - // Note: The argument here is replaced with JSON in PHP by \AmpProject\AmpWP\MobileRedirection::add_mobile_redirect_script(). + // Note: The argument here is replaced with a JSON object literal in PHP by \AmpProject\AmpWP\MobileRedirection::add_mobile_redirect_script(). AMP_MOBILE_REDIRECTION, ) );