Microsoft Windows Edge自定义修改请求参数拦截所有或者指定请求
支持自定义拦截请求(见附件例子)
async void InitializeAsync()
{
await webView2Browser.EnsureCoreWebView2Async(null);
webView2Browser.CoreWebView2.WebMessageReceived += UpdateAddressBar;
await webView2Browser.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
await webView2Browser.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
}
void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
String uri = args.TryGetWebMessageAsString();
textBoxUrl.Text = uri;
webView2Browser.CoreWebView2.PostWebMessageAsString(uri);
}
// Add a filter to select all resource types under http://www.example.com
webView.CoreWebView2.AddWebResourceRequestedFilter(
"http://www.example.com", CoreWebView2WebResourceContext.All);
webView.CoreWebView2.WebResourceRequested += delegate (
object sender, CoreWebView2WebResourceRequestedEventArgs args) {
CoreWebView2WebResourceContext resourceContext = args.ResourceContext;
// Only intercept the document resources
if (resourceContext != CoreWebView2WebResourceContext.Document)
{
return;
}
CoreWebView2HttpRequestHeaders requestHeaders = args.Request.Headers;
requestHeaders.SetHeader("Custom", "Value");
}
// Add a filter to select all resource types under http://www.example.com
m_webView->AddWebResourceRequestedFilter(
L"http://www.example.com/", COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL);
m_webView->add_WebResourceRequested(
Callback<ICoreWebView2WebResourceRequestedEventHandler>(
[this](
ICoreWebView2* sender,
ICoreWebView2WebResourceRequestedEventArgs* args) {
COREWEBVIEW2_WEB_RESOURCE_CONTEXT resourceContext;
CHECK_FAILURE(args->get_ResourceContext(&resourceContext));
// Only intercept the document resources
if (resourceContext != COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT)
{
return S_OK;
}
// Set a custom header to the document request.
wil::com_ptr<ICoreWebView2WebResourceRequest> request;
CHECK_FAILURE(args->get_Request(&request));
wil::com_ptr<ICoreWebView2HttpRequestHeaders> headers;
request->get_Headers(&headers);
headers->SetHeader(L"Custom", L"Value");
return S_OK;
})
.Get(),
&m_webResourceRequestedToken);
Custom management of network requests - Microsoft Edge Development | Microsoft Learn