@@ -8,7 +8,6 @@ import { INVALID_URLS } from '@/utils/constants'
88import { CONTEXT_MENU , CONTEXT_MENU_ITEM_TRANSLATE_PAGE } from '@/utils/context-menu'
99import logger from '@/utils/logger'
1010import { bgBroadcastRpc } from '@/utils/rpc'
11- import { registerBackgroundRpcEvent } from '@/utils/rpc/background-fns'
1211import { isTabValid } from '@/utils/tab'
1312import { registerDeclarativeNetRequestRule } from '@/utils/web-request'
1413
@@ -37,8 +36,7 @@ export default defineBackground(() => {
3736 } )
3837
3938 const setPopupStatusBasedOnUrl = async ( tabId : number , url : string ) => {
40- const isValidUrl = / h t t p s ? : \/ \/ / . test ( url ?? '' )
41- if ( ! isValidUrl || unAttachedTabs . has ( tabId ) || INVALID_URLS . some ( ( regex ) => regex . test ( url ) ) ) {
39+ if ( INVALID_URLS . some ( ( regex ) => regex . test ( url ) ) ) {
4240 await browser . action . setPopup ( { popup : 'popup.html' } )
4341 }
4442 else {
@@ -84,14 +82,8 @@ export default defineBackground(() => {
8482 } )
8583 } )
8684
87- const unAttachedTabs = new Set < number > ( )
88-
8985 browser . runtime . onInstalled . addListener ( async ( ) => {
9086 logger . debug ( 'Extension Installed' )
91- const tabs = await browser . tabs . query ( { currentWindow : true } )
92- for ( const tab of tabs ) {
93- tab . id && unAttachedTabs . add ( tab . id )
94- }
9587 await browser . contextMenus . removeAll ( )
9688 for ( const menu of CONTEXT_MENU ) {
9789 browser . contextMenus . create ( {
@@ -100,6 +92,23 @@ export default defineBackground(() => {
10092 contexts : menu . contexts ,
10193 } )
10294 }
95+ // inject content script into all tabs which are opened before the extension is installed
96+ const tabs = await browser . tabs . query ( { } )
97+ for ( const tab of tabs ) {
98+ if ( tab . id && tab . url ) {
99+ const tabUrl = tab . url
100+ if ( INVALID_URLS . some ( ( regex ) => regex . test ( tabUrl ) ) ) continue
101+ await browser . scripting . executeScript ( {
102+ files : [ '/content-scripts/content.js' ] ,
103+ target : { tabId : tab . id } ,
104+ world : 'ISOLATED' ,
105+ } ) . then ( ( ) => {
106+ logger . info ( 'Content script injected' , { tabId : tab . id } )
107+ } ) . catch ( ( error ) => {
108+ logger . error ( 'Failed to inject content script' , { tabId : tab . id , error } )
109+ } )
110+ }
111+ }
103112 } )
104113
105114 browser . contextMenus . onClicked . addListener ( async ( info , tab ) => {
@@ -112,9 +121,5 @@ export default defineBackground(() => {
112121 }
113122 } )
114123
115- registerBackgroundRpcEvent ( 'ready' , ( tabId ) => {
116- unAttachedTabs . delete ( tabId )
117- } )
118-
119124 logger . info ( 'Hello background!' , { id : browser . runtime . id } )
120125} )
0 commit comments