window.addEventListener('load', function) not working in angular application

1.3k views Asked by At

I have a subscription in a component of angular app where I need to download PDF file from response.

I am downloading PDF file after window.open() method has been called and later need to close current(new opened) tab via window.close() method.

window.close() method should run only after load event of window object is completed and PDF file is downloaded, but load event is not firing.

Here is code:

.subscribe(
    (res: any) => {
        if (response) {

                const formData: string = response.replace(/\n/g, '');
                const win: any = window.open('', '_blank'); // open new tab
                win.document.write(formData); 
                // NOT FIRED
                win.addEventListener('load', () => {
                    // submit form received in response
                        win.close();         // NOT CALLED
                    },
                    false
                    );
                    
                }
            }
        );
        

Note: I don't want to use setTimeout() function and call window.close() there since the time for downloading might vary based on different factors (such as browser environment, file size and et.c.), otherwise it's possible to solve this issue by using:

    win?.setTimeout(() => {
        win?.close();
    }, 3000);

So, what is wrong here? Any help is appreciated.

1

There are 1 answers

1
Manuel Tomás On

Looking at your code, it looks like you are adding the load listener on window and not on win which is probably what you want.

Here is the way I normally use.

I do not have a way to test this with pdf files, but the way I download files received with an http request is by using Blob. Like this:

const blob = new Blob([res], {type : 'application/pdf'});
const url = window.URL.createObjectURL(blob);
window.open(url);

From my experience with other file types, this opens the tab, starts downloading the file and closes (while the file is still downloading).

Feel free to ask for clarification if needed!