@@ -4,25 +4,30 @@ import { uniqueId } from 'lodash'
4
4
import styles from '../style/components/IFrame.module.css'
5
5
interface Props {
6
6
src : string
7
- onPageChanged : ( page : string , hash : string ) => void
7
+ onPageChanged : ( page : string , hash : string , title ?: string ) => void
8
8
onHashChanged : ( hash : string ) => void
9
+ onTitleChanged : ( title : string ) => void
9
10
onNotFound : ( ) => void
10
11
}
11
12
12
13
export default function IFrame ( props : Props ) : JSX . Element {
13
14
const iFrameRef = useRef < HTMLIFrameElement > ( null )
14
15
15
16
const onIframeLoad = ( ) : void => {
16
- if ( iFrameRef . current == null ) {
17
+ if ( iFrameRef . current === null ) {
17
18
console . error ( 'iFrameRef is null' )
18
19
return
19
20
}
20
21
21
- // remove the hashchange event listener to prevent memory leaks
22
+ // remove the event listeners to prevent memory leaks
22
23
iFrameRef . current . contentWindow ?. removeEventListener (
23
24
'hashchange' ,
24
25
hashChangeEventListener
25
26
)
27
+ iFrameRef . current . contentWindow ?. removeEventListener (
28
+ 'titlechange' ,
29
+ titleChangeEventListener
30
+ )
26
31
27
32
const url = iFrameRef . current ?. contentDocument ?. location . href
28
33
if ( url == null ) {
@@ -69,6 +74,10 @@ export default function IFrame(props: Props): JSX.Element {
69
74
'hashchange' ,
70
75
hashChangeEventListener
71
76
)
77
+ iFrameRef . current . contentWindow ?. addEventListener (
78
+ 'titlechange' ,
79
+ titleChangeEventListener
80
+ )
72
81
73
82
const parts = url . split ( '/doc/' ) . slice ( 1 ) . join ( '/doc/' ) . split ( '/' )
74
83
const urlPageAndHash = parts . slice ( 2 ) . join ( '/' )
@@ -77,12 +86,13 @@ export default function IFrame(props: Props): JSX.Element {
77
86
: urlPageAndHash . length
78
87
const urlPage = urlPageAndHash . slice ( 0 , hashIndex )
79
88
const urlHash = urlPageAndHash . slice ( hashIndex )
89
+ const title = iFrameRef . current ?. contentDocument ?. title
80
90
81
- props . onPageChanged ( urlPage , urlHash )
91
+ props . onPageChanged ( urlPage , urlHash , title )
82
92
}
83
93
84
94
const hashChangeEventListener = ( ) : void => {
85
- if ( iFrameRef . current == null ) {
95
+ if ( iFrameRef . current === null ) {
86
96
console . error ( 'hashChangeEvent from iframe but iFrameRef is null' )
87
97
return
88
98
}
@@ -102,6 +112,20 @@ export default function IFrame(props: Props): JSX.Element {
102
112
props . onHashChanged ( hash )
103
113
}
104
114
115
+ const titleChangeEventListener = ( ) : void => {
116
+ if ( iFrameRef . current === null ) {
117
+ console . error ( 'titleChangeEvent from iframe but iFrameRef is null' )
118
+ return
119
+ }
120
+
121
+ const title = iFrameRef . current ?. contentDocument ?. title
122
+ if ( title == null ) {
123
+ return
124
+ }
125
+
126
+ props . onTitleChanged ( title )
127
+ }
128
+
105
129
return (
106
130
< iframe
107
131
ref = { iFrameRef }
0 commit comments