-
Notifications
You must be signed in to change notification settings - Fork 220
/
hook.ts
54 lines (42 loc) · 1.44 KB
/
hook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import {useMemo, useEffect} from 'react';
import {ClientApplication} from '@shopify/app-bridge';
import {History} from '@shopify/app-bridge/actions';
import {LocationOrHref} from './types';
import {
getSelfWindow,
getTopWindow,
getOrigin,
MODAL_IFRAME_NAME,
} from './globals';
export default function useRoutePropagation(
app: ClientApplication<any>,
location: LocationOrHref,
) {
const history = useMemo(() => History.create(app), [app]);
useEffect(() => {
const selfWindow = getSelfWindow();
const topWindow = getTopWindow();
const renderedInTheTopWindow = selfWindow === topWindow;
const renderedInAModal = selfWindow.name === MODAL_IFRAME_NAME;
if (renderedInTheTopWindow || renderedInAModal) {
return;
}
const normalizedLocation = getNormalizedURL(location);
/*
We delete this param that ends up unnecassarily stuck on
the iframe due to oauth when propagating up.
*/
normalizedLocation.searchParams.delete('hmac');
const {pathname, search, hash} = normalizedLocation;
const locationStr = `${pathname}${search}${hash}`;
history.dispatch(History.Action.REPLACE, locationStr);
}, [history, location]);
}
function getNormalizedURL(location: LocationOrHref) {
const origin = getOrigin();
if (typeof location === 'string') {
return new URL(location, origin);
}
const {pathname, search, hash} = location;
return new URL(`${pathname}${search}${hash}`, origin);
}