5
我想通過在「導航前」 -events修改標題使用WatiN框架來改變用戶代理字符串。我認爲我非常接近解決方案,但出於某種原因,我在一段時間訪問過url之後,被重定向到了下面代碼的空白頁面。定製BeforeNavigate事件在華廷瀏覽器
如果我註釋掉定製BeforeNavigate事件,瀏覽器不重定向到空白頁,這使我相信,我的自定義事件需要稍加修改。你有什麼想法可能是什麼問題?
要重現該問題,請下載華廷和運行下面的代碼:
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;
}
}
}
你需要改變所有的請求的用戶代理,或只是直接導航請求的頁面就夠了嗎?另外,您是否需要在單個測試/過程中將其多次更改爲不同的內容? –
@BenAaronson對不起,我沒有得到這個通知出於某種原因。導航到頁面的請求就足夠了。是的,每個「IE」實例都需要能夠擁有自己的頭文件。 – Johan