@@ -5,12 +5,15 @@ import openDevToolsWindow from './openWindow';
55let panelConnections = { } ;
66let tabConnections = { } ;
77let catchedErrors = { } ;
8+ let unsubscribeList = { } ;
9+ let isMonitored = false ;
810
911window . syncOptions = syncOptions ; // Used in the options page
1012
1113const naMessage = { type : 'NA' } ;
1214
1315function initPanel ( msg , port ) {
16+ monitorInstances ( true ) ;
1417 panelConnections [ msg . tabId ] = port ;
1518 if ( msg . tabId !== store . id ) return naMessage ;
1619}
@@ -25,11 +28,14 @@ function initInstance(msg, port) {
2528 store . liftedStore . instances [ id ] = msg . instance ;
2629 store . id = id ;
2730 if ( typeof id === 'number' ) chrome . pageAction . show ( id ) ;
28- return { type : 'START' } ;
31+ if ( isMonitored ) return { type : 'START' } ;
2932}
3033
3134function disconnect ( port ) {
32- if ( ! port . sender . tab && port . id === chrome . runtime . id ) return ;
35+ if ( ! port . sender . tab && ! port . id ) {
36+ monitorInstances ( false ) ;
37+ return ;
38+ }
3339 const id = getId ( port ) ;
3440 delete tabConnections [ id ] ;
3541 if ( panelConnections [ id ] ) panelConnections [ id ] . postMessage ( naMessage ) ;
@@ -128,3 +134,51 @@ export function toContentScript(action) {
128134 tabConnections [ id ] . postMessage ( message ) ;
129135 }
130136}
137+
138+ function monitorInstances ( shouldMonitor ) {
139+ if (
140+ ! shouldMonitor && Object . getOwnPropertyNames ( unsubscribeList ) . length !== 0
141+ || isMonitored === shouldMonitor
142+ ) return ;
143+
144+ Object . keys ( tabConnections ) . forEach ( id => {
145+ tabConnections [ id ] . postMessage ( { type : shouldMonitor ? 'START' : 'STOP' } ) ;
146+ } ) ;
147+ isMonitored = shouldMonitor ;
148+ }
149+
150+ function getTab ( cb ) {
151+ chrome . tabs . query ( {
152+ active : true ,
153+ windowId : chrome . windows . WINDOW_ID_CURRENT
154+ } , ( tab ) => {
155+ cb ( tab [ 0 ] . id ) ;
156+ } ) ;
157+ }
158+
159+ const unsubscribeMonitor = ( tabId ) => ( ) => {
160+ if ( ! unsubscribeList [ tabId ] ) return ;
161+ unsubscribeList [ tabId ] ( ) ;
162+ delete unsubscribeList [ tabId ] ;
163+ if ( Object . getOwnPropertyNames ( panelConnections ) . length === 0 ) {
164+ monitorInstances ( false ) ;
165+ }
166+ } ;
167+
168+ // Expose store to extension's windows (monitors)
169+ window . getStore = ( cb ) => {
170+ monitorInstances ( true ) ;
171+ getTab ( ( tabId ) => {
172+ cb ( {
173+ ...store ,
174+ liftedStore : {
175+ ...store . liftedStore ,
176+ subscribe ( ...args ) {
177+ const unsubscribe = store . liftedStore . subscribe ( ...args ) ;
178+ unsubscribeList [ tabId ] = unsubscribe ;
179+ return unsubscribe ;
180+ }
181+ }
182+ } , unsubscribeMonitor ( tabId ) ) ;
183+ } ) ;
184+ } ;
0 commit comments