[SalesForce] How to redirect Visualforce page automatically

I have custom button which when clicked redirects to VF page, VF page calls some controller,

But I want as soon as custom button is clicked it should process to VF page waits for 2 secs and then redirect back to detail page of the record.

How to achieve that? Not getting any help from google

Best Answer

This is the most simple way I could imagine. Other alternatives abound, as well.

<apex:page controller="Controller" action="{!action}">
    <script>
        window.setTimeout(function() {
            window.history.go(-1);
        }, 2000); // 2 seconds
    </script>
    We did as you asked. Redirecting back in 2 seconds.
</apex:page>

As a side note, I'd avoid DML this way, because it does open up the possibility of XSS attacks (however unlikely that would be). Instead, offer the button here as a means of confirmation, then return when you're done. Alternatively, simply perform the work from the button itself. There's really no need to show a page for just two seconds.


You can also show a waiting dialog while you're waiting:

<apex:page controller="Controller">
Please wait...
<script>
function done() {
    window.history.go(-1); // Or elsewhere
}
</script>
<apex:form>
<apex:actionFunction name="doAction" action="{!doAction}" oncomplete="done()" />
</apex:form>
<script>
doAction();
</script>
</apex:page>

Feel free to use a spinner or something instead of just a generic "please wait" message to give the illusion that something is happening (which, something is happening, but we want the user to be reassured).