@@ -148,6 +148,48 @@ export namespace MessageHandling {
148148 } > {
149149 action : string ;
150150 }
151+ export function doFetch ( url : string ) : Promise < string > {
152+ if ( 'fetch' in window && window . fetch !== undefined ) {
153+ return fetch ( url ) . then ( r => r . text ( ) ) as unknown as Promise < string > ;
154+ }
155+
156+ return new Promise < string > ( ( resolve , reject ) => {
157+ const xhr = new window . XMLHttpRequest ( ) ;
158+ xhr . open ( 'GET' , url ) ;
159+ xhr . onreadystatechange = ( ) => {
160+ if ( xhr . readyState === 4 ) {
161+ if ( xhr . status >= 200 && xhr . status < 300 ) {
162+ resolve ( xhr . responseText ) ;
163+ } else {
164+ reject ( xhr . status ) ;
165+ }
166+ }
167+ }
168+ xhr . send ( ) ;
169+ } ) ;
170+ }
171+ export function backgroundFetch ( message : CRMAPIMessageInstance < string , {
172+ url : string ;
173+ onFinish : number ;
174+ } > ) {
175+ const url = message . data . url ;
176+ doFetch ( url ) . then ( ( responseText ) => {
177+ modules . globalObject . globals . sendCallbackMessage ( message . tabId ,
178+ message . tabIndex , message . id , {
179+ err : false ,
180+ args : [ false , responseText ] ,
181+ callbackId : message . data . onFinish
182+ } ) ;
183+ } ) . catch ( ( err ) => {
184+ modules . globalObject . globals . sendCallbackMessage ( message . tabId ,
185+ message . tabIndex , message . id , {
186+ // Don't signify an error so the promise can be handled
187+ err : false ,
188+ args : [ true , `Failed with status ${ err } ` ] ,
189+ callbackId : message . data . onFinish
190+ } ) ;
191+ } ) ;
192+ }
151193
152194 async function handleRuntimeMessage ( message : CRMAPIMessageInstance < string , any > ,
153195 messageSender ?: _browser . runtime . MessageSender ,
@@ -240,6 +282,9 @@ export namespace MessageHandling {
240282 modules . Storages . clearStorages ( ) ;
241283 await modules . Storages . loadStorages ( ) ;
242284 break ;
285+ case 'fetch' :
286+ await backgroundFetch ( message ) ;
287+
243288 }
244289 respond && respond ( response ) ;
245290 }
0 commit comments