2016-12-29 41 views
0

我需要將自定義用戶代理和身份驗證令牌插入到從webview製作的所有請求中。攔截從webview製作的HttpRequests是否可能?攔截Web視圖請求Xaml

回答

0

在UWP中,我們應該能夠使用WebView.NavigateWithHttpRequestMessage方法將WebView導航到具有POST請求和HTTP標頭的URI。

在WebView中有一個NavigationStarting事件,它發生在WebView導航到新內容之前。所以我們應該能夠將WebViewNavigationStartingEventArgs.Cancel屬性設置爲true以取消導航。

例如:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    NavigateWithHeader(new Uri("http://www.whoishostingthis.com/tools/user-agent/")); 
} 

private void NavigateWithHeader(Uri uri) 
{ 
    var requestMsg = new Windows.Web.Http.HttpRequestMessage(HttpMethod.Get, uri); 
    string ua = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; 
    requestMsg.Headers.Add("User-Agent", ua); 
    MyWebView.NavigateWithHttpRequestMessage(requestMsg); 
    MyWebView.NavigationStarting += Wb_NavigationStarting; 
} 

private void Wb_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
{ 
    MyWebView.NavigationStarting -= Wb_NavigationStarting; 
    args.Cancel = true; 
    NavigateWithHeader(args.Uri); 
} 
+0

是否有可能攔截從Javascript也提出的要求。我想在webview中加載下面提到的內容。 javascript將生成詳細頁面,但問題在於生成的html內容,在src中沒有爲圖像和js文件指定協議(http或https)。我想手動添加這個頁面來工作 – Prince

+0

「 – Prince