I need to download a file that is accessed after submitting a form. I can run the file download with the function page.click(selector)
but then it comes on its way browser.close()
and closes it before it finishes downloading.
How can I run the download to know when it finished and then close the browser?
I'm using headless: false
it for now, but I need it to work in both modes.
Between the click and the browser.close() is the delay of the download of the file from the server, right? Then it would be better to control the download request so that once you have it in memory, moving it from there to the one saved on the PC is direct. You could use a function like this:
That function would return a promise with the blob of the file. Remember that to be able to do this function successfully you must carefully inspect the anatomy of the request that makes the equivalent click that you mentioned.
Then you could create a url with that blob:
With that you can now assign it to the "href" attribute of an "ancor" elementwith "download" attribute. To then execute its click method and download to the pc, but since the data is already local, the process is immediate, so browser.close() will no longer beat you.
The download process would generally be something like this:
However, for that do not forget to put before the download path with:
I haven't tested the code so maybe there is some syntax error, but the idea itself should work since these requests are usually recurring and this is usually the correct way or at least that's how we do it in my work.
Anyway, I hope I have helped you. Regards and)
I finally got around it using
node-fetch
and some utilities to write files.field.download
is my html selector which I import from an object.Node-fetch: https://github.com/node-fetch/node-fetch
The other utilities are available in node.
I did what Darwin told me. Right now I have this but I have the same initial problem. Before saving the pdf file the browser closes