Issue Avoiding Js Alert in Cefsharp browser
Asked Answered
K

2

5

I am trying to avoid js alert on a page as it breaks the flow and the browser is stuck on that page until the popup is clicked.

I added Class as shown on sample:

public class JsDialogHandler : IJsDialogHandler
{
    public bool OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage)
    {
        return true;
    }

    public bool OnJSBeforeUnload(IWebBrowser browserControl, IBrowser browser, string message, bool isReload, IJsDialogCallback callback)
    {
        return true;
    }

    public void OnResetDialogState(IWebBrowser browserControl, IBrowser browser)
    {

    }

    public void OnDialogClosed(IWebBrowser browserControl, IBrowser browser)
    {

    }
}

And i assign to the Chromium browser as:

  CefSharp.Cef.Initialize(new CefSharp.CefSettings());

                browser = new CefSharp.WinForms.ChromiumWebBrowser(CustomLinks[0].ToString());

                JsDialogHandler jss = new JsDialogHandler();
                browser.JsDialogHandler = jss;

The thing is when alert is supposed to show it does run the OnJSDialog event. But then the browser turns white and is just stuck and trying to find a way around but not much is available online..

Any suggestions?

Khamsin answered 19/1, 2017 at 18:17 Comment(3)
You need to execute the callback, read the xml doc for instructions.Firer
@Firer can you please post link for that.Khamsin
Just navigate to the method in visual studio and read the documentationFirer
M
8

In the OnJSDialog method of your handler, make sure that you call Continue(...) on the callback:

public bool OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) {
  callback.Continue(true);
  return true;
}
Manchineel answered 21/1, 2017 at 19:41 Comment(0)
S
1

If you simply want to disable javascript alerts, there is parameter suppressMessage just for that:

// Implementation of IJsDialogHandler
public bool OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage)
{
    suppressMessage = true;
    return false;
}
// All other methods should do nothing or return false.
Squashy answered 27/3, 2018 at 19:37 Comment(1)
The best answer IMO.Dunkle

© 2022 - 2024 — McMap. All rights reserved.