javascriptvirtual-file

Using javascript client-side, how can I display a "virtual folder" (= a coherent collection of html,img,js with relative paths)?


I want to display autonomous "sites" on a html page (Say "root"). Those "sites" contain a landing page : index.html and a collection of *.css, .js,.png)
By autonomous, I mean those sites does not have external dependencies and all paths are relative = you can copy them in any directory or host them anywhere and they'll work.
Those sites are zipped in a archive that contains all necessary files. Say I got no problem with the download and got all the files in memory (as path/uint8 array)

How could I display the site in a safe way ? I can parse the index.html, change all the src and href for data-url of the original files and load it in an iframe. It works rather well but it breaks where there are scripts like this

if (extension == "pdf")
 img.src = "images/thumb-pdf.png"

Is there any way to control the url served by the iframe? Some kind of proxy? Can I intercept "images/thumb-pdf.png" to serve MemoryCacheOfAllFiles["images/thumb-pdf.png"].toDataURL() instead ?

PS: Of course I got no control on those sites and I can't store them on server (it would be to easy)


Solution

  • Proxy are possible in javascript one got to use a worker and listen for the "fetch" event to push the virtual content.

    html pushed in iframe:

    ...
    navigator.serviceWorker.register('worker.js').then(function() {
        logInstall('Installing...');
      })
    ...
    

    worker.js:

    ...
    self.onfetch = function(event) {
      var cached = (mycache[event.request.url]); // do we have content
      if (cached)
        event.respondWith(new Response(cached.content,{
          headers:{"Content-Type",cached.mimetype}
        }
      else
        event.respondWith(fetch(event.request));
    }
    ...
    

    Full code by mozilla to unzip and serve content
    https://serviceworke.rs/cache-from-zip.html