@@ -58,12 +58,16 @@ if (json) {
5858 } ) ;
5959 } ) ;
6060
61- window . addEventListener ( 'message' , event => {
62- if ( event . data && event . data . hash ) {
63- window . location . hash = event . data . hash ;
64- } else {
61+ const setHash = debounce ( hash => {
62+ if ( hash ) {
63+ window . location . hash = hash ;
64+ } else if ( window . location . hash ) {
6565 history . pushState ( '' , document . title , window . location . pathname + window . location . search ) ;
6666 }
67+ } , 300 ) ;
68+
69+ const onMessage = event => {
70+ setHash ( event . data . hash ) ;
6771
6872 if ( event . data && event . data . openSettings ) {
6973 if ( chrome . runtime . openOptionsPage ) {
@@ -72,11 +76,43 @@ if (json) {
7276 window . open ( chrome . runtime . getURL ( 'pages/settings.html' ) ) ;
7377 }
7478 }
75- } ) ;
79+ } ;
7680
77- window . addEventListener ( 'hashchange' , ( ) => {
81+ window . addEventListener ( 'message' , onMessage ) ;
82+
83+ const onHashChange = ( ) => {
7884 iframe . contentWindow . postMessage ( {
7985 hash : window . location . hash
8086 } , '*' ) ;
87+ } ;
88+
89+ window . addEventListener ( 'hashchange' , onHashChange ) ;
90+
91+ window . addEventListener ( 'beforeunload' , ( ) => {
92+ window . removeEventListener ( 'message' , onMessage ) ;
93+ window . removeEventListener ( 'hashchange' , onHashChange ) ;
8194 } ) ;
8295}
96+
97+ /**
98+ * Debounce
99+ * @param {Function } func
100+ * @param {number } wait
101+ * @returns {Function }
102+ */
103+ function debounce ( func , wait ) {
104+ let timer = null ;
105+
106+ return function ( ...args ) {
107+ const onComplete = ( ) => {
108+ func . apply ( this , args ) ;
109+ timer = null ;
110+ } ;
111+
112+ if ( timer ) {
113+ clearTimeout ( timer ) ;
114+ }
115+
116+ timer = setTimeout ( onComplete , wait ) ;
117+ } ;
118+ }
0 commit comments