-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiframe-loader.tsx
60 lines (52 loc) · 1.61 KB
/
iframe-loader.tsx
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
55
56
57
58
59
60
import React, { FC, IframeHTMLAttributes, useMemo, useEffect } from 'react'
import qs from 'query-string'
import { UPDATE } from './constants'
type IframeHtmlProps = IframeHTMLAttributes<HTMLIFrameElement>
type IframeLoaderProps = IframeHtmlProps & {
/**
* Prefix used for query search.
*
* @default 'path'
*/
queryPrefix?: string
/**
* Iframe source.
*/
src: string
}
export const IframeLoader: FC<IframeLoaderProps> = ({ queryPrefix = 'path', src, ...props }) => {
const source = useMemo(() => {
const queryData = qs.parse(window.location.search)
const urlData = qs.parseUrl(src)
const query = qs.stringify({
...urlData.query,
path: queryData[queryPrefix] || urlData.query.path,
})
return `${urlData.url}?${query}`
}, [queryPrefix, src])
useEffect(() => {
const onMessage = (message: { data: string }) => {
if (message.data === '') {
return
}
try {
const data = JSON.parse(message.data)
if (data.method === UPDATE) {
const urlData = qs.parseUrl(window.location.href)
urlData.query[queryPrefix] = data.payload.path
const nextQuery = qs.stringify(urlData.query)
const nextUrl = `${urlData.url}?${nextQuery}`
window.history.replaceState(null, '', nextUrl)
}
} catch (error) {
// Suppress error while parsing.
}
}
window.addEventListener('message', onMessage)
return () => {
window.removeEventListener('message', onMessage)
}
}, [])
// eslint-disable-next-line jsx-a11y/iframe-has-title
return <iframe {...props} src={source} />
}