简体   繁体   English

C#-当网页上的JavaScript调用window.close()时,关闭System.Windows.Forms.WebBrowser。

[英]C# - Close a System.Windows.Forms.WebBrowser when the javascript on the webpage calls window.close()

I'm launching a website on a C# System.Windows.Forms.WebBrowser, and after performing the task on the website, the website's javascript calls a function consisting of this: 我正在C#System.Windows.Forms.WebBrowser上启动网站,并在网站上执行任务后,网站的javascript调用了一个包含以下内容的函数:

window.open("Closer.html", '_self');

Closer.html contains this: Closer.html包含以下内容:

<script type="text/javascript">
window.close();
</script>

And this works perfectly on an external browser like IE or chrome. 这在IE或chrome等外部浏览器上完美运行。 But my winforms browser remains open. 但是我的winforms浏览器仍然打开。 I have researched this and found that others have experienced this problem, and have been unable to find a solution. 我对此进行了研究,发现其他人也遇到了此问题,并且无法找到解决方案。

I'd like to either have my C# System.Windows.Forms.WebBrowser class detect that the javascript function window.close() has been called and subsequently do a simple this.close() call, or I could modify the javascript Closer.html to close the System.Windows.Forms.WebBrowser window if that can be done. 我想让我的C#System.Windows.Forms.WebBrowser类检测到javascript函数window.close()已被调用,然后进行简单的this.close()调用,或者我可以修改javascript Closer。 html以关闭System.Windows.Forms.WebBrowser窗口(如果可以的话)。

Try this out. 试试看 Set your browser to allow navigation. 将浏览器设置为允许导航。 Either from designer or via code. 可以是设计师提供的,也可以是通过代码提供的。

wb.AllowNavigation = true;

Then, see if this event is fired: 然后,查看是否触发了此事件:

private void wb_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    if (e.Url.AbsolutePath.IndexOf("closer.html", StringComparison.OrdinalIgnoreCase) > 1)
        this.Close();
}

Obviously, you need to hook up the navigating event. 显然,您需要连接导航事件。 Again, via the designer or via code. 同样,通过设计人员或通过代码。

wb.Navigating += wb_Navigating;

Edit: That should work for your specific case, however I do see a good answer posted here to a similar issue. 编辑:这应该适用于您的特定情况,但是我确实在此处看到了类似问题的良好答案。

How can I be notified when a window is closed by window.close (javascript)? 当window.close(javascript)关闭窗口时,如何通知我?

Using the code found there, and modifying the html, you should be able to handle this. 使用在那里找到的代码,并修改html,您应该能够处理此问题。 Instead of doing the redirect, you COULD just call window.close(). 不用执行重定向,您可以只调用window.close()。 Then, the webbrowser should notice and act accordingly. 然后,网络浏览器应注意并采取相应措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM