Releases: ioa747/NetWebView2Lib
v1.5.0
Version 1.5.0
Advanced Networking & Download Management
This update introduces deep integration with Chromium's networking layer and programmatic control over the download lifecycle.
Added
- HTTP Status Code Tracking (DispId 5):
OnWebResourceResponseReceived(statusCode, reasonPhrase, requestUrl): [Event] Captures the HTTP status code for every resource request (e.g., 404, 500), enabling precise error handling in AutoIt.HttpStatusCodeEventsEnabled: (195) [Property] Master switch to enable or disable the status code event entirely.HttpStatusCodeDocumentOnly: (196) [Property] Filters status code events to only trigger for the main document (Default: True). This prevents event floods that cause GUI deadlocks in AutoIt.
- Custom Download Management (DispIds 204 - 211):
SetDownloadPath(path): (204) [Method] Forces downloads to a specific folder or file. If a directory is provided, the filename is automatically appended.IsDownloadUIEnabled: (205) [Property] Control visibility of the browser's download bubble.OnDownloadStarting: (208) [Event] Intercepts downloads. Features a simplified contract (URI, DefaultPath). Overrides are now handled via dedicated properties/methods (SetDownloadPath,IsDownloadHandled).OnDownloadStateChanged: (209) [Event] Real-time progress (bytes) and state updates.CancelDownloads(uri): (210) [Method] Cancels downloads. Ifuriis empty or omitted, cancels all active downloads.IsDownloadHandled: (211) [Property] Set toTrueduringOnDownloadStartingto suppress the default download UI.ActiveDownloadsList: (214) [Property] Returns a pipe-separated string of all active download URIs.
- Enhanced Export & Snapshot Engine (DispIds 201, 207):
CaptureSnapshot(cdpParameters): (201) [Method] Direct access to CDP snapshots (e.g., MHTML).ExportPageData(format, filePath): (207) [Method] Simplified HTML/MHTML export. Note: Moved to DispId 207 to distinguish from raw CDP snapshots.
- Binary Data Support:
DecodeB64ToBinary(base64Text): (206) [Method] Decodes Base64 to raw byte arrays (binary).
- Manual Download Mode: Added logic to
DownloadStartingthat checksIsDownloadHandled. If set toTrueby AutoIt during the event wait loop, the native Edge download is cancelled (e.Cancel = true), allowing AutoIt to handle the download externally (e.g., viaInetGet). - Download Sync-Wait: A 600ms synchronization loop ensures that property changes in AutoIt are correctly picked up by C# before the download proceeds or is cancelled.
- UnLockWebView Method: Added
UnLockWebView()(215) to re-enable restricted features previously disabled byLockWebView(). - Zoom Control: Added
IsZoomControlEnabled(212) [Property] specify if zoom (Ctrl+Wheel) is enabled. - Scrollbar Control: Added
IsScrollbarEnabled(213) [Property] Toggle scrollbars via CSS overflow injection.
Fixed
- Smart Auto-Fill: Updated
Initializeto automatically calculate initial parent dimensions when 0 width/height are provided. Note: Dynamic resizing remains disabled unless$oWeb.SetAutoResize(True)is called explicitly. - Naming Consistency: Standardized method names (e.g.,
CaptureSnapshot) across C# and COM interfaces. - Build Efficiency: Resolved IDE warnings (
CS0067) and unnecessary#pragmadirectives. - GUI Deadlock (HttpStatusCode): Fixed a critical issue where an flood of 404 resource responses for sub-elements (images, CSS, scripts) would overwhelm the AutoIt event loop, causing the GUI to freeze. Added robust tracking to ensure these events are filtered to the main document by default.
- Download Race Condition Fix: Added
Application.DoEvents()to theOnDownloadStartingevent to ensure AutoIt property overrides (DownloadResultPath,IsDownloadHandled) are synchronized correctly before the download begins. - Automatic Directory Creation: Implemented automatic folder creation for custom download paths if the target directory does not exist.
- Event Fixes: Wired up the
OnZoomChangedevent to correctly trigger when the browser zoom level is modified.
v1.4.3
Version 1.4.3 - (2026-01-20)
COM Robustness & Performance
This update focuses on deepening COM compatibility and resolving assembly discovery issues in AutoIt, along with specialized scraping tools for the main showcase.
Fixed
- COM Event Discovery (0x80028017): Resolved the "Field name not defined" error in AutoIt by explicitly requiring the 3rd parameter in
ObjEventfor .NET-exported interfaces. Documented the necessity of interface names (e.g.,IWebViewEvents) for reliable connection point binding. - Smart AutoResize (Dynamic Margins): Refined
SetAutoResizeto automatically calculate margins based on thewidthandheightpassed toInitialize. This allows users to request absolute sizes (e.g., leaving a specific gap for a status bar) and have those gaps preserved naturally as the parent window resizes.
Added
- Additional Browser Arguments (DispId 100):
- Added
AdditionalBrowserArgumentsproperty. Allows passing command-line switches (e.g.,--disable-gpu,--mute-audio,--proxy-server="...") to the Chromium engine. Note: This must be set before callingInitialize().
- Added
- Advanced JSON Manipulation (JsonParser) (DispIds 225 - 228):
GetTokenCount(path): (225) Returns the count of array items or object properties.GetKeys(path, delimiter): (226) Returns a delimited string of all property names for an object.SortArray(path, key, desc): (227) Sorts a JSON array in-place based on a specific key.SelectUnique(path, key): (228) Removes duplicates from a JSON array based on a key's value.
- Advanced Export & PDF Management (DispIds 201 - 203):
ExportPageData(format, filePath): (201) Saves the current page as HTML (0) or MHTML (1). The MHTML snapshots are captured via CDP and parsed natively. Supports returning content as a string iffilePathis empty.PrintToPdfStream(): (202) Captures the page as a PDF and returns a Base64 string directly to AutoIt, eliminating temporary file requirements.HiddenPdfToolbarItems: (203) [Property] Bitwise control for the PDF viewer's toolbar (e.g., hiding print/save buttons).
Changed
- Interface Protocol (Dual Binding): Upgraded
IWebViewActionsandIJsonParsertoInterfaceIsDual. This enables support for both Early Binding (performance) and Late Binding (flexibility) simultaneously, improving overall stability in diverse COM environments. SetTokenValue(JsonParser) Upgrade: Now supports Deep Creation (automatic creation of parent objects) and Smart Typing (automatic conversion of "true", "false", "null" and numbers, while preserving leading zeros in strings like "0123").WebViewManager.csReorganization: Completely restructured the 1500+ line class into 17 logical regions for better IDE maintainability and code folding.GetArrayLength(JsonParser): Refactored to internally use the more robustGetTokenCountlogic.
v1.4.2
Version 1.4.2 - (2026-01-06)
⚡ Synchronous Execution & Enhanced Automation
This major update bridges the gap between the asynchronous nature of WebView2 and the procedural logic of AutoIt, introducing synchronous script results and specialized automation controls.
Added
-
Synchronous Scripting (DispId 188):
- ExecuteScriptWithResult(string script): (188) Executes JavaScript and returns the result directly to AutoIt in a single line. Includes a 5-second safety timeout and automatic JSON unescaping for clean string results.
-
Automation & Layout Controls (DispIds 189, 191, 193):
-
AddInitializationScript(string script): (187) Injects a script that persists across navigations and refreshes, executing automatically on every new document.
-
SetAutoResize(bool enabled): (189) Enables "Smart Anchor" resizing using Win32 subclassing. Works with non-.NET parent containers (like AutoIt) and maintains top-left offsets. Sends "WINDOW_RESIZED" to AutoIt on completion.
-
ExecuteScriptOnPage(string script): (191) A dedicated method for immediate, high-priority script execution on the current page.
-
ClearCache(): (193) Targeted removal of Disk Cache and Local Storage to ensure the browser always loads the freshest content.
-
-
Unified Context Menu Handling (DispIds 190, 194):
-
OnContextMenuRequested(link, x, y, selection): (190) [Event] Provides a rich, simplified context event with direct access to the URL, coordinates, and selected text under the cursor. -
CustomMenuEnabled: (194) [Property] A Master switch to enable or disable custom menu interception.
-
-
Advanced Data Binding (DispIds 185 - 186):
- BindJsonToBrowser(variableName): (185) Securely binds internal JSON data to a JavaScript variable. Updated to ensure 100% COM compatibility with legacy registrations.
- SyncInternalData(json, bindTo): (186) High-performance helper that parses raw JSON and binds it to a browser variable in a single atomic operation.
-
Integrated Base64 Support (JsonParser) (DispIds 222 - 224):
- EncodeB64 / DecodeB64: (222, 223) Native Base64 processing directly within the JSON parser, eliminating the need for external Base64 libraries.
- DecodeB64ToFile(b64, path): (224) Decodes a Base64 stream and saves it directly to disk (perfect for screenshots and binary downloads).
Changed
-
Automation & Layout Controls (DispIds 115, 116, 184):
-
InjectCss(string cssCode): (115) Inject CSS (Persistence to run on every refresh)
-
AddInitializationScript(string script): (116) Clear Injected CSS.
-
ClearInjectedCss(): (184) Injects a script that persists across navigations and refreshes, executing automatically on every new document.
-
Improvements
-
Legacy Compatibility: The context menu logic has been completely redesigned to support both the new parameter-based event (v1.4.2) and the legacy JSON event (v1.4.1) simultaneously.
-
Robustness: JSON parsing now automatically trims whitespace, and all browser interactions include enhanced internal try-catch blocks. Added a Global COM Error Handler in the showcase demo for professional diagnostics.
-
Unified Messaging:
WINDOW_RESIZEDnow includes explicit dimensions (Width|Height) in the data payload for better reactive UI control. -
Robust Auto-Resizing: Replaced
Dock.Fillwith a Native Subclassing (NativeWindow) mechanism to interceptWM_SIZEmessages directly from the OS, ensuring perfect synchronization even with non-WinForms parent handles.
v1.4.1.1
v1.4.1
Version 1.4.1 - (2026-01-03)
🚀 Data Intelligence & JSON Manipulation
This update transforms the NetJson.Parser into a full-featured JSON management suite, allowing for complex data merging and structure inspection directly from AutoIt.
Added
-
Advanced JSON Methods (DispIds 214 - 221):
-
Merge(string jsonContent): (214) Performs a deep merge of a new JSON string into the existing structure. UsesUnionstrategy for arrays to prevent duplicates. -
MergeFromFile(string filePath): (215) Efficiently reads a JSON file from disk and merges it directly into the current session. -
GetTokenType(string path): (216) Returns the .NET/Newtonsoft type of a specific node (e.g., Object, Array, String, Integer, Boolean). Essential for dynamic data validation. -
RemoveToken(string path): (217) Allows dynamic deletion of specific keys or array elements, providing full CRUD (Create, Read, Update, Delete) capabilities -
Search(string query): (218) Executes a JSONPath query and returns a JSON array of all matching tokens. Enables powerful filtering and deep searching with a single call. -
Flatten(): (219) Flattens the JSON structure into a single-level object with dot-notated paths. -
CloneTo(string parserName): (220) Clones the current JSON data to another named parser instance. -
FlattenToTable(string colDelim, string rowDelim): (221) Flattens the JSON structure into a table-like string with specified delimiters.
-
-
Web Content Extraction (DispId 200):
GetInnerText(): (200) Retrieves the entire visible text content (innerText) of the document. The result is returned asynchronously via theOnMessageReceivedevent with theInner_Text|prefix. This enables powerful web scraping and content analysis without manual DOM parsing.
Improvements
-
Enhanced Error Handling: All new JSON and Web methods are wrapped in try-catch blocks to prevent COM crashes when dealing with malformed data or invalid DOM states.
-
Memory Efficiency:
MergeFromFileutilizes local C# file streams, reducing the memory overhead for the calling AutoIt script when handling large configuration files. -
Unified Messaging: Content extraction now follows the standardized
Command|Dataformat, making it easier to route messages in the AutoIt event loop.
v1.4.0
Added
-
Unified Settings & Permissions (New Property System)
- Implemented a comprehensive set of Read/Write properties to control WebView2 behavior directly from AutoIt.
- Properties (DispIds 170-179, 183):
AreDevToolsEnabled(170): Toggle Developer Tools.AreDefaultContextMenusEnabled(171): Control native context menus.AreDefaultScriptDialogsEnabled(172): Suppress or allow alerts/prompts.AreBrowserAcceleratorKeysEnabled(173): Manage browser shortcuts.IsStatusBarEnabled(174): Toggle the status bar.- ZoomFactor (175): Direct access to zoom level.
BackColor(176): Set background color using Hex strings (e.g., "0xFFFFFF").AreHostObjectsAllowed(177): Control JS bridge access.Anchor(178): Manage control resizing behavior.BorderStyle(179): Placeholder for border style configuration.AreBrowserPopupsAllowed(183): Control new window/popup allowance.
- Methods (DispIds 180-182, 184):
-
SetZoomFactor (180): Helper method for zoom.
-
OpenDevToolsWindow (181): Programmatically open DevTools.
-
WebViewSetFocus (182): Force focus to the WebView control.
-
**
AddInitializationScript** (184): Injects and manages persistent JS logic.
-
-
Custom Context Menu System
- Implemented
OnContextMenuCOM event (DispId 6) to intercept user right-clicks. - Added data payload support providing context metadata (Coordinates, Kind, TagName, Selection, Source URL, Link URL) via JSON.
- Sent as raw JSON string (prefixed with "JSON:") to avoid Base64 overhead.
- Implemented
-
Focus Management Overhaul
OnBrowserGotFocus(DispId 11): Native event triggering when WebView gains focus.OnBrowserLostFocus(DispId 12): Native event triggering when focus leaves the WebView hierarchy.- Refactored logic to use
AreDevToolsEnabledstyle properties instead of legacy timers for cleaner integration.
-
Utilities
- EncodeURI (DispId 165): Native UTF-8 encoding for safe URL parameter generation.
- DecodeURI (DispId 166): Native decoding to convert percent-encoded strings.
- EncodeB64 (DispId 167): Native encoding (UTF-8) -> Base64.
- DecodeB64 (DispId 168): Native decoding Base64 -> String (UTF8).
-
Navigation Lifecycle Events
OnNavigationStarting(DispId 2): Intercepts and validates URLs before loading.OnNavigationCompleted(DispId 3): Detailed navigation status andWebErrorStatus.
-
State Synchronization
OnTitleChanged(DispId 4): Real-time synchronization of document title.OnURLChanged(DispId 13): Real-time tracking of URL changes.OnZoomChanged(DispId 10): Event fired when zoom level changes.
-
Property Getters
-
GetSource (DispId 135) &
GetDocumentTitle (DispId 134).
-
GetCanGoBack (DispId 162) &
GetCanGoForward (DispId 163).
-
GetBrowserProcessId (DispId 164).
-
-
Permanent JavaScript Injection System
-
Implemented
AddInitializationScript (DispId 184): Allows permanent injection of JavaScript libraries (like
bridge.js) that persist across navigations and page refreshes. -
Added automated script lifecycle management using
AddScriptToExecuteOnDocumentCreatedAsync. -
Integrated Script ID Tracking: The library now remembers the last injected script ID to allow clean replacement or removal, preventing memory leaks and script duplication.
-
Fixed
- Focus Bounce Issue Resolved where internal focus changes triggered false "LostFocus" events. Implemented robust checks using
BeginInvokeandGetFocuswithIsChildverification. - CS1061 Compile Error Corrected
TitleChangedto standardDocumentTitleChangedevent mapping. - Context Menu JSON Fixed JSON escaping for special characters in selection text and URLs.
Changed
-
Refactored Event Registration Cleaned up
RegisterEvents to remove legacy AdBlock/Context Menu duplication while preserving functionality.
-
DispId Standardization Re-mapped
OnURLChangedto DispId 13 to avoid conflicts. -
Extension Management
-
AddExtension (DispId 150) now triggers a notification event with the internal ID for better lifecycle management via
RemoveExtension (DispId 151).
-
Version 1.3.0
Version 1.3.0 - (2025-12-25)
Added
-
Multi-Instance Support: Added the ability to create and manage multiple independent WebView2 instances within the same AutoIt application.
-
Extension Support: Introduced the
AddExtensionmethod, allowing the loading of unpacked browser extensions (Manifest V2 and V3) per instance. -
Independent User Profiles: Each instance now supports a unique
UserDataFolder, enabling isolated cookies, cache, and browser history (e.g.,Profile_1,Profile_2). -
Context Menu Control: Added
SetContextMenuEnabledto programmatically enable or disable the right-click menu. -
DevTools Management: Added
SetDevToolsEnabledto toggle access to the browser's developer tools.
Fixed
-
Event Routing: Resolved an issue where JavaScript bridge messages were cross-talking between instances; messages are now correctly routed via unique prefixes (e.g.,
Web1_,Web2_). -
Resource Locking: Improved the
Cleanup()method to ensure all WebView2 processes and profile files are properly released upon closing. -
Initialization Sequence: Fixed a race condition where calling methods before the engine was fully ready caused crashes; events now properly wait for the
INIT_READYsignal.
Changed
-
Event-Driven Architecture: Refactored the communication layer to be 100% event-driven, eliminating the need for
Sleep()or polling loops. -
Bridge Logic: Optimized the
.NETtoAutoItbridge to handle high-frequency messaging without UI blocking. -
Resizing Logic: Updated the recommended implementation to use
WM_SIZEfor smoother synchronization between AutoIt GUI containers and the WebView2 engine.