Skip to content

Commit

Permalink
Persist URL fragment during client-side mobile redirection and guard …
Browse files Browse the repository at this point in the history
…against infinite redirect (#5775)
  • Loading branch information
westonruter committed Jan 12, 2021
1 parent 950396c commit b41fbb9
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions assets/src/mobile-redirection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/ampproject/amp-wp/issues/5767>.
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,
) );

0 comments on commit b41fbb9

Please sign in to comment.