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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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() {
    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">
            alert('Hello World');
        <apex:outputText rendered="{!not showAlert}" id="noAlert">
            No alert this time, sorry. Random value was: {!numberValue}.
        <apex:actionPoller interval="5" action="{!doRandomAlert}" reRender="form" />

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.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x