In an extension, I'm trying to fetch an array of local resources and pass them from the page script of a local HTML file, to its content script, to the background script, and ultimately to an extension page for display. It starts in the page script because the resources are local.
If one resource is fetched, it works without error and the extension page displays the resource. When the length of the array of resources is greater than one, it works only if the fetch requests are written out as if the length was known in advance. If array.map
is used to convert the array of resource paths to an array of fetches to be used in a Promise.all, the fetch data is empty when it reaches the background script, although all the logs in the page and content script display the files.
The code is below. con_script.return_fetch
is a function in the content script placed on the page script's window using cloneInto
to pass the data to the background script. o
is just an object of two properties, src
the array of source paths and caller
the tab.id of the tab with the extension page loaded that initiated the event requesting to display the resources. The Promise.all
adds a third property status
depending upon whether the set all resolves or not.
If o.src
is written to the console from this page script or the associated content script, it is an array of blobs as it should be. But in the background script it contains the paths instead of the blobs. This only happens if use Array.map
.
Why would using Array.map
result in the changes to object o
not being recognized in the background script? I'm repeating myself, but the exact same code works correctly if the commented out Promise.all
is run instead. But, of course, the number of resources in each request is unknown.
Is there another method in addition to Array.map
to convert the array of sources to an array of fetch promises?
Thank you.
Promise.all( o.src.map( ( v, i ) => { fetch_i( v, i ); } ) )
//Promise.all( [ fetch_i( o.src[ 0 ], 0 ), fetch_i( o.src[ 1 ], 1 ) ] )
.then( ( r ) =>
{
o.status = 'resolve';
window.con_script.return_fetch( o );
} )
.catch( ( e ) =>
{
o.status = 'reject';
o.src = e;
window.con_script.return_fetch( o );
} );
function fetch_i( v, i )
{
return new Promise( ( resolve, reject ) =>
{
fetch( v )
.then( response => response.blob() )
.then( ( myBlob ) =>
{
o.src[ i ] = myBlob; // Overwrite the source path with the blob.
resolve();
} )
.catch( ( e ) =>
{
reject( e );
} );
} ); // close promise
} // close fetch_i