Commit a8bdb94c authored by Robert Knight's avatar Robert Knight

Check type of `window.navigation` global before using it

Fix a crash on web pages which define a global variable called `navigation`,
which conflicts with the `window.navigation` entry point for the Navigation API.

If such a variable exists, the existing fallback to `window.history` will be
used instead.

Fixes #5324
parent 63897c36
/* global Navigation */
import { ListenerCollection } from '../../shared/listener-collection'; import { ListenerCollection } from '../../shared/listener-collection';
/** /**
...@@ -38,6 +39,28 @@ function stripFragment(url) { ...@@ -38,6 +39,28 @@ function stripFragment(url) {
return url.replace(/#.*/, ''); return url.replace(/#.*/, '');
} }
/**
* Return the Navigation API entry point for the current window.
*
* This is a wrapper around `window.navigation` which checks both that the
* object exists and has the expected type. See also
* https://github.com/hypothesis/client/issues/5324.
*
* @return {EventTarget|null}
*/
export function getNavigation() {
const navigation = /** @type {any} */ (window).navigation;
if (
// @ts-expect-error - Navigation API is missing from TS
typeof Navigation === 'function' &&
// @ts-expect-error
navigation instanceof Navigation
) {
return navigation;
}
return null;
}
/** /**
* Utility for detecting client-side navigations of an HTML document. * Utility for detecting client-side navigations of an HTML document.
* *
...@@ -76,8 +99,7 @@ export class NavigationObserver { ...@@ -76,8 +99,7 @@ export class NavigationObserver {
} }
}; };
// @ts-expect-error - TS is missing Navigation API types. const navigation = getNavigation();
const navigation = window.navigation;
if (navigation) { if (navigation) {
this._listeners.add(navigation, 'navigatesuccess', () => this._listeners.add(navigation, 'navigatesuccess', () =>
checkForURLChange() checkForURLChange()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment