Skip to content

CefSharp handle alerts, confirms, and prompts

CefSharp Handle alerts, confirms, and prompts

I recently needed to make use of CefSharp library to implement my own Chrome-based browser and had to hook or handle javascript alerts, confirms and prompts. This was how I did it, in case any of you find yourself needing it.

You will need to implement your own class which extends the IJsDialogHandler interface

public class JsHandler : IJsDialogHandler
{
    public void OnDialogClosed(IWebBrowser browserControl, IBrowser browser)
    {
        throw new NotImplementedException();
    }

    public bool OnJSAlert(IWebBrowser browser, string url, string message)
    {
        MessageBox.Show("Alert Detected. Url : " + url + " \n message : " + message);
        return false;
    }

    public bool OnJSBeforeUnload(IWebBrowser browserControl, IBrowser browser, string message, bool isReload, IJsDialogCallback callback)
    {
        throw new NotImplementedException();
    }

    public bool OnJSConfirm(IWebBrowser browser, string url, string message, out bool retval)
    {
        MessageBox.Show("Confirm Detected. Url : " + url + " \n message : " + message);
        retval = false;
        return false;
    }

    public bool OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage)
    {
        throw new NotImplementedException();
    }

    public bool OnJSPrompt(IWebBrowser browser, string url, string message, string defaultValue, out bool retval, out string result)
    {
        MessageBox.Show("Prompt Detected. Url : " + url + " \n message : " + message);
        retval = false;
        result = "";
        return false;
    }

    public void OnResetDialogState(IWebBrowser browserControl, IBrowser browser)
    {
        throw new NotImplementedException();
    }
}

And then in your ChromiumWebBrowser instance,

JsHandler jh = new JsHandler();
browser.JsDialogHandler = jh;

 

 

Enjoyed the content ? Share it with your friends !
Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.