gpt4 book ai didi

c# - webBrowser 控件停止来自网站的 javascript 警报

转载 作者:搜寻专家 更新时间:2023-11-01 04:42:29 25 4
gpt4 key购买 nike

我正在使用 Web 浏览器控件在 VS 2010 C# 中开发 Windows 窗体应用程序。我的目标是在这个网站中自动导航,但是当我在某个点时,网站会弹出一个 javascript 警报,它将停止自动化,直到我按下 OK 按钮。我有点通过在它弹出时模拟回车键来解决这个问题,但应用程序应该保持专注以使其工作。我的问题是,是否有任何方法可以从网站上终止此自定义 javascript 警报(我无权访问侧面,从客户端将其终止)以使其不显示或以任何其他方式解决此问题?显示的 javascript 警报(消息框)不是错误,是该网站的程序员出于某种原因放置在那里的 javascript 警报。

最佳答案

您可以尝试使用 Navigated 事件并在页面加载之前拦截 DocumentText 以删除 alert(...); 引用.

来自 MSDN 上的导航页面:

Handle the Navigated event to receive notification when the WebBrowser control has navigated to a new document. When the Navigated event occurs, the new document has begun loading, which means you can access the loaded content through the Document, DocumentText, and DocumentStream properties.

这是一些代码:

using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Your.App
{
public class PopupSuppress
{
WebBrowser _wb;
public PopupSupress()
{
_wb = new WebBrowser();
_wb.Navigated += new WebBrowserNavigatedEventHandler(_wb_Navigated);
}

void _wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string alertRegexPattern = "alert\\([\\s\\S]*\\);";
//make sure to only write to _wb.DocumentText if there is a change.
//This will prompt a reloading of the page (and another 'Navigated' event) [see MSDN link]
if(Regex.IsMatch(_wb.DocumentText, alertRegexPattern))
_wb.DocumentText = Regex.Replace(_wb.DocumentText, alertRegexPattern, string.Empty);
}
}
}

来源/资源:

关于c# - webBrowser 控件停止来自网站的 javascript 警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12408249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com