Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser and javascript window.close()

Tags:

browser

c#

.net

If I host a WebBrowser in my application, and a javascript code in the web page shown on my WebBrowser calls window.close() and I click "Yes" on the prompt, my WebBrowser disappears but my form stays open.

I don't want to disable javascript, and not pressing "Yes" is obviously not the solution. What's the best way to handle this? Is this something I can cancel programmatically even after the user presses "Yes"? And also, are there any other javascript tricks like window.close() that could mess up my application that I should be aware of? (My application uses a WebBrowser to search the web, so every possible javascript code should be considered.)

like image 748
Juan Avatar asked Apr 04 '11 07:04

Juan


1 Answers

In WPF you can catch WM_CLOSE message by attaching to WebBrowser's message loop.

public MainWindow()
{
    InitializeComponent();
    webBrowser.MessageHook += webBrowser_MessageHook;
}

IntPtr webBrowser_MessageHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    switch(msg)
    {
        case 0x0010:    // WM_CLOSE
            handled = true; // cancel event here
            // do additional stuff here    
            break;
    }
    return IntPtr.Zero;
}
like image 64
user3433274 Avatar answered Sep 21 '22 16:09

user3433274