|
53 | 53 | return;
|
54 | 54 | }
|
55 | 55 |
|
56 |
| - const url = new URL( location.href ); |
| 56 | + const locationUrlObject = new URL( location.href ); |
| 57 | + const amphtmlUrlObject = new URL( ampUrl ); |
57 | 58 |
|
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 ) ) { |
59 | 64 | // If the noamp query param is present, remember that redirection should be disabled.
|
60 | 65 | sessionStorage.setItem( disabledStorageKey, '1' );
|
61 |
| - } else { |
| 66 | + } else if ( amphtmlUrlObject.href !== locationUrlObject.href ) { |
62 | 67 | // 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>. |
63 | 71 | window.stop(); // Stop loading the page! This should cancel all loading resources.
|
64 | 72 |
|
65 | 73 | // Replace the current page with the AMP version.
|
66 |
| - location.replace( ampUrl ); |
| 74 | + location.replace( amphtmlUrlObject.href ); |
67 | 75 | }
|
68 | 76 | }(
|
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(). |
70 | 78 | AMP_MOBILE_REDIRECTION,
|
71 | 79 | ) );
|
0 commit comments