22import '.' ;
33import { type ContentScript } from 'webext-content-scripts/types' ;
44import { injectContentScript } from 'webext-content-scripts' ;
5- import { type ActiveTab , onActiveTab } from './active-tab.js' ;
5+ import { type ActiveTab , onActiveTab , possiblyActiveTabs } from './active-tab.js' ;
66import { isContentScriptRegistered } from './utils.js' ;
77
8+ type InjectionDetails = {
9+ tabId : number ;
10+ frameId : number ;
11+ url : string ;
12+ } ;
13+
14+ const gotNavigation = typeof chrome === 'object' && 'webNavigation' in chrome ;
15+
816const scripts = chrome . runtime . getManifest ( ) . content_scripts as ContentScript ;
917
10- async function injectToTab ( { id, origin} : ActiveTab ) : Promise < void > {
18+ async function injectToTabUnlessRegistered ( { id, origin} : ActiveTab ) : Promise < void > {
1119 if ( id && ! ( await isContentScriptRegistered ( origin ) ) ) {
1220 // Warning: This might cause duplicate injections on frames of activeTabs with different origins. Some details in:
1321 // https://github.com/fregante/webext-dynamic-content-scripts/pull/44
@@ -16,4 +24,34 @@ async function injectToTab({id, origin}: ActiveTab): Promise<void> {
1624 }
1725}
1826
19- onActiveTab ( injectToTab ) ;
27+ async function injectIfActive (
28+ { tabId, frameId, url} : InjectionDetails ,
29+ ) : Promise < void > {
30+ if ( possiblyActiveTabs . has ( tabId ) && ! ( await isContentScriptRegistered ( url ) ) ) {
31+ await injectContentScript ( { tabId, frameId} , scripts ) ;
32+ }
33+ }
34+
35+ async function tabListener (
36+ tabId : number ,
37+ { status} : chrome . tabs . TabChangeInfo ,
38+ { url} : chrome . tabs . Tab ,
39+ ) : Promise < void > {
40+ // Only status updates are relevant
41+ // No URL = no permission
42+ if ( status === 'loading' && url ) {
43+ await injectIfActive ( { tabId, url, frameId : 0 } ) ;
44+ }
45+ }
46+
47+ function init ( ) {
48+ onActiveTab ( injectToTabUnlessRegistered ) ;
49+
50+ if ( gotNavigation ) {
51+ chrome . webNavigation . onCommitted . addListener ( injectIfActive ) ;
52+ } else {
53+ chrome . tabs . onUpdated . addListener ( tabListener ) ;
54+ }
55+ }
56+
57+ init ( ) ;
0 commit comments