我试图使用WatiN框架通过在“before navigation”事件中修改头文件来更改用户代理字符串。我认为我已经非常接近解决方案了,但出现以下代码后,几秒钟后URL被访问后,我不知何故会被重定向到一个空白页面。
如果我注释掉自定义的BeforeNavigate事件,浏览器就不会重定向到空白页面,这导致我相信我的自定义事件需要做一些微小的修改。您有什么想法可能是问题所在吗?
要复制此问题,请下载WatiN并运行以下代码:
@Noseratio的建议也给我留下了一个空白页面:
如果我注释掉自定义的BeforeNavigate事件,浏览器就不会重定向到空白页面,这导致我相信我的自定义事件需要做一些微小的修改。您有什么想法可能是问题所在吗?
要复制此问题,请下载WatiN并运行以下代码:
private SHDocVw.InternetExplorerClass _ieInstance;
private const string UserAgent =
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64)" +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153" +
"Safari/537.36\r\n";
bool _renavigating;
private IE _browser;
private void Form1_Load(object sender, EventArgs e)
{
_ieInstance = _ieInstance = new SHDocVw.InternetExplorerClass();
//_ieInstance.BeforeNavigate2 += BeforeNavigate;
_browser = new IE(_ieInstance);
_browser.GoTo("http://www.procato.com/my+headers/");
}
void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
headers += string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;
_ieInstance.Navigate((string)url,
(string)targetFrameName, (byte[])postData, (string)headers);
}
else
{
_renavigating = false;
}
}
}
@Noseratio的建议也给我留下了一个空白页面:
readonly SynchronizationContext _sc = SynchronizationContext.Current;
void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
var newHeaders = string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;
string thatUrl = (string)url;
object thatFlags = flags;
object thatTargetFrameName = targetFrameName;
object thatPostData = postData;
object thatHeaders = (headers != null && headers != Type.Missing &&
headers != System.DBNull.Value) ?
(headers.ToString() + newHeaders) : newHeaders;
_sc.Post(_ =>
{
((SHDocVw.IWebBrowser)pDisp).Navigate(
thatUrl,
ref thatFlags,
ref thatTargetFrameName,
ref thatPostData,
ref thatHeaders);
}, null);
}
else
{
_renavigating = false;
}
}
}