Home >Backend Development >C++ >How to Efficiently Generate Dynamic HTML Using .NET's WebBrowser and Async/Await?
This article explores how to dynamically generate HTML code using the WebBrowser class of System.Windows.Forms or the HTMLDocument interface of the Microsoft HTML Object Library assembly.
The user initially tried to use the System.Windows.Forms.WebBrowser class but encountered limitations in getting the rendered HTML code. I had the same problem trying to access the code through the mshtml.HTMLDocument interface.
Users ruled out these methods and sought alternatives, exploring using the WebBrowser's properties to get the required data, but acknowledging the shortcomings of this approach.
The proposed solution combines the WebBrowser class and async/await programming to efficiently poll for changes in the current HTML snapshot of the page while checking the WebBrowser.IsBusy property. Key considerations include:
The following code demonstrates the LoadDynamicPage method of the encapsulated solution:
<code class="language-csharp">async Task<string> LoadDynamicPage(string url, CancellationToken token) { // 导航和DocumentCompleted事件处理 var tcs = new TaskCompletionSource<bool>(); WebBrowserDocumentCompletedEventHandler handler = (s, arg) => tcs.TrySetResult(true); using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true)) { this.webBrowser.DocumentCompleted += handler; try { this.webBrowser.Navigate(url); await tcs.Task; // 等待DocumentCompleted } finally { this.webBrowser.DocumentCompleted -= handler; } } // 获取根元素 var documentElement = this.webBrowser.Document.GetElementsByTagName("html")[0]; // 异步轮询当前HTML更改 var html = documentElement.OuterHtml; while (true) { // 异步等待 await Task.Delay(500, token); // 如果WebBrowser繁忙,则继续轮询 if (this.webBrowser.IsBusy) continue; var htmlNow = documentElement.OuterHtml; if (html == htmlNow) break; // 未检测到更改,结束轮询循环 html = htmlNow; } // 认为页面已完全渲染 token.ThrowIfCancellationRequested(); return html; }</code>
To enable HTML5 rendering in Internet Explorer 10 and above, use the browser feature controls shown below:
<code class="language-csharp">private static void SetFeatureBrowserEmulation() { if (LicenseManager.UsageMode != LicenseUsageMode.Runtime) return; var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, 10000, RegistryValueKind.DWord); }</code>
The above is the detailed content of How to Efficiently Generate Dynamic HTML Using .NET's WebBrowser and Async/Await?. For more information, please follow other related articles on the PHP Chinese website!