Closing the tab in browser after calling a ashx handler

2.5k views Asked by At

Besides it is similar question I cannot find solution to my problem. I am also not very skilled with JavaScript.

I create a ashx handler for downloading files from sharepoint site. All works fine when file in database exist. If file does not exist I should pop-up alert.

In ashx I create:

 var r = context.Response;
        var attachmentID = context.Request.QueryString[QueryKeyID];
        int id = 0;
        if (!String.IsNullOrEmpty(attachmentID))
        {
            id = Convert.ToInt32(attachmentID);

            DocKey k = new DocKey() { id = id };


            DocImage od = MyWebService.GetDocImage(k);
            String newFile = "document.doc";

            r.ContentType = GetMimeTypeByFileName(newFile);
            r.AppendHeader("Content-Type", GetMimeTypeByFileName(newFile));
            r.AppendHeader("content-disposition", "attachment; filename=" + newFile);
            r.BufferOutput = false; //Stream the content to the client, no need to cache entire streams in memory...
            r.BinaryWrite(od.image);
            r.End();
        }
        else
        {
            r.Write("<script type='text/javascript'>alert('no doc');</script>");
            r.End();

        }

If file exist it open open/save dialog and tab is closed after clicking any option. But if file does not exist alert is shown and the blank tab does not disappear.

Download starts after clicking this link which is in gridView :

<asp:TemplateField HeaderText="">
                <ItemTemplate>
                    <asp:HiddenField ID="hdnkey" runat="server" Value='<%# getKey(Eval("Key")) %>' />
                    <a href="/_LAYOUTS/UserHandler/AttachmentHandler.ashx?ID='<%# getKey(Eval("Key")) %>'" target="_blank">download</a>      
                </ItemTemplate>
            </asp:TemplateField>

I want to make auto cloasing the blank tab after alert.

3

There are 3 answers

2
LittleSweetSeas On BEST ANSWER

Try this:

r.Write("<script type='text/javascript'>alert('brak dokumentu w bazie');window.close();</script>");

It should work unless it's blocked by some security setting on the browser.

1
Murali Murugesan On

You cannot do like that, since you are opening a url, a new request.

Even if you have the below code

 r.AppendHeader("Content-Type","text/html");

 r.Write("<script type='text/javascript'>alert('no doc');</script>");

This code will show you the alert in new window and in the existing window.

It is better to detect a document exists or not at the time of rendering linkes in grid. If not available, show Not Found text

0
ankit soni On
context.Response.Write("<script type='text/javascript'>function closeCurrentTab(){var conf=confirm('Are you sure, you want to close this tab?');if(conf==true){close();}}</script>");

context.Response.Write("<script type='text/javascript'>closeCurrentTab();</script>");