Search code examples
reactjsprogressive-web-appsservice-workerweb-share-target

Unable to get the file when using Share Target API


I have a PWA and want share phone images with it...

Let's say, someting like this example app https://scrapbook-pwa.web.app/ available here https://github.com/GoogleChrome/samples/tree/gh-pages/web-share

I have the current content on files:

manifest.json

  "share_target": {
    "action": "/shareFile",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "files": [
        {
          "name": "data",
          "accept": ["image/*"]
        }
      ]
    }
  }

service-worker.js This listener to catch every request to "/shareFile" and handle it as I want.

self.addEventListener("fetch", async (event) => {
  console.log("[SW FETCH]");

  const url = new URL(event.request.url);

  if (event.request.method === "POST" && url.pathname === "/shareFile") {
    broadcastChannel.postMessage({ alert: "[SW IS POST] shareFile" });

    event.waitUntil(
      (async function () {
        console.log("[SW WAIT UNTIL]");

        const formData = await event.request.formData();
        const filesReceived = formData.getAll("data");
        const fileReceived = filesReceived[0];

        console.log("[BROADCASTING]", fileReceived);
        broadcastChannel.postMessage({ file: fileReceived });

        await handleCacheFile(fileReceived);
      })()
    );

    event.respondWith(Response.redirect("/settings", 303));
  }

  return;
});

Settings.js For test purposes...

<form action="/shareFile" method="post" encType="multipart/form-data">
    <input type="file" ref={inputRef} name="data" />

    <button type="submit">Submit</button>

    <button type="button" onClick={() => handleUpload()}>
        OnClick
    </button>
</form>

The point is... I installedd the PWA app on my phone via a https page, when I use the form and upload the file everything works as it should, the broadcastChannel is sent, the event.waitUntil is executed, and also the Response.redirect.

BUT, when I share the image with the app, only the Response.redirect appears to work. Everything else not appears to work.

Debugging is kinda harn since I executed all on the phone. But I tried all I could and still can't get the file on the app like the scrapbook-pwa does...


Solution

  • Ok so... I've done a lot of tests and finaly realize why is not behaving as it should...

    I posted the app on the Firebase Hosting, with the redirect for the index.html enable. Aparently the mechanism Firebase use to do this redirect ends up in lost of some data when sharing content with the PWA.

    I uploaded the exact same code on Netlify and just setup the _redirects file with /* /index.html 200 and it worked...