Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist URL fragment during client-side mobile redirection and guard against infinite redirect #5775

Merged
merged 2 commits into from
Jan 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
) );