Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...