I have command button while clicking the button it will redirect to VF page where it will renderas data as excel also it will open a site.Once the excel download is completed,the window needs to be closed.

VF Page

 <apex:commandlink id="export" action="{!export}" onclick="redirect();" rerender="null"  style="display: none;" > 
  <apex:commandButton style="background:#0065d3; border-radius: 10px; width: 300px; font-weight: bold;float: right; color: white; height: 40px;" value="Exporting" oncomplete = "testFun();return false;"/>                                 </apex:commandlink>

   function testFun() {

function redirect() {
            window.open("{!$Site.BaseUrl}" + "{!successSite}", "_blank");


 public PageReference export() {
        string urlString;        
        urlString = System.URL.getSalesforceBaseURL().toExternalForm()+'/apex/ExporttoExcel';
        PageReference retURL = new PageReference(urlString);
        return retURL;

Here,before downloading the excel the window gets closed.Without using setTimeout function how can i close the current window once excel download completed.Please help me out !!


If you want to download a csv by opening a new window and close as soon as csv downloads then you can use the below code for the commandButton.

VF Page:

    <apex:commandButton value="Download CSV" id="export" onClick="window.open('{!selectedReportDownloadUrl}');" />


public String getSelectedReportDownloadUrl() {
   string urlString;        
   urlString = System.URL.getSalesforceBaseURL().toExternalForm()+'/apex/ExporttoExcel';
   return urlString; 

Code written above will open a new window and download the csv file. Once the csv is downloaded newly opened window will be closed automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.