Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

c# - WebBrowser and javascript window.close()

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...