[SalesForce] Call Javascript function from apex method

I have some buttons on my visualforce page which onclick, run a javascript function.

Sometimes however, the javascript function will need to run without the user actually clicking on the button. I need to call the javascript function from an apex method. How can I achieve this?

Best Answer

You can reRender scripts that should be run when conditions are met. I wrote up an arbitrary example where you have (approximately) a 50% chance of getting a popup dialog, and 50% chance of just plain text. Every five seconds, the server is called again, and you may get a dialog popup. This requires no user interaction.

public class showAlertRandom {
    public boolean showAlert { get; set; }
    public Decimal numberValue { get; set; }
    public showAlertRandom() {
        doRandomAlert();
    }
    public void doRandomAlert() {
        numberValue = Math.random();
        showAlert = numberValue < 0.5;
    }
}

<apex:page controller="showAlertRandom" showHeader="true">
    <apex:form id="form">
        <apex:outputText rendered="{!showAlert}" id="alert">
            <script>
            alert('Hello World');
            </script>
        </apex:outputText>
        <apex:outputText rendered="{!not showAlert}" id="noAlert">
            No alert this time, sorry. Random value was: {!numberValue}.
        </apex:outputText>
        <apex:actionPoller interval="5" action="{!doRandomAlert}" reRender="form" />
    </apex:form>
</apex:page>

How it works:

Though Apex Code can't call JavaScript directly, it can set a variable to render a script block that can run arbitrary code. On each render, when the variable is true, an alert is produced. I wouldn't try doing this inside a closure or the middle of a script block, as you'll probably get very unpredictable results. You could dispatch a custom event or call some global function, if you prefer. You can use this technique anywhere reRender is supported, such as on a commandLink, commandButton, and actionFunction.