Skip to content

Commit ced89bf

Browse files
authored
Initial Release of NetWebView2Lib v1.3.0
### Added - **Multi-Instance Support**: Added the ability to create and manage multiple independent WebView2 instances within the same AutoIt application. - **Extension Support**: Introduced the `AddExtension` method, 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 `SetContextMenuEnabled` to programmatically enable or disable the right-click menu. - **DevTools Management**: Added `SetDevToolsEnabled` to 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_READY` signal. ### 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 `.NET` to `AutoIt` bridge to handle high-frequency messaging without UI blocking. - **Resizing Logic**: Updated the recommended implementation to use `WM_SIZE` for smoother synchronization between AutoIt GUI containers and the WebView2 engine.
1 parent 4eeeb1f commit ced89bf

24 files changed

Lines changed: 2772 additions & 2 deletions
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
With the release of **v1.3.0**, you can now load browser extensions (unpacked) independently for each WebView2 instance. This is perfect for adding Ad-blockers, Dark Mode, or custom developer tools to your automation scripts.
2+
3+
---
4+
5+
#### 1. Prepare your Extension Library
6+
7+
WebView2 requires extensions to be in **Unpacked** format (a folder containing the `manifest.json` file).
8+
9+
1. Create a folder named `Extensions_Lib` in your project directory.
10+
11+
2. Download your desired extension (e.g., **uBlock Origin Lite** or **Dark Reader**).
12+
13+
3. If you have a `.crx` file, extract it using a ZIP tool.
14+
15+
4. Your structure should look like this:
16+
17+
Plaintext
18+
19+
```
20+
YourProject/
21+
├── MyScript.au3
22+
└── Extensions_Lib/
23+
└── DarkReader/
24+
├── manifest.json <-- This must be in the root of the folder
25+
├── background.js
26+
└── ...
27+
```
28+
29+
30+
#### 2. Implementation in AutoIt
31+
32+
Extensions must be loaded **after** the engine is ready (`INIT_READY`) but **before** or during the initial navigation.
33+
34+
AutoIt
35+
36+
```
37+
; Example for Instance 2
38+
Func Web2_OnMessageReceived($sMsg)
39+
Local $aParts = StringSplit($sMsg, "|")
40+
Local $sCommand = StringStripWS($aParts[1], 3)
41+
42+
Switch $sCommand
43+
Case "INIT_READY"
44+
; Define the path to your unpacked extension
45+
Local $sExtPath = @ScriptDir & "\Extensions_Lib\DarkReader"
46+
47+
; Load the extension for this specific instance
48+
$oWeb2.AddExtension($sExtPath)
49+
50+
; Navigate to your target site
51+
$oWeb2.Navigate("https://www.autoitscript.com/forum/")
52+
53+
Case "EXTENSION_LOADED"
54+
ConsoleWrite("+> Success: Extension loaded in Web2!" & @CRLF)
55+
56+
Case "ERROR"
57+
If StringInStr($sMsg, "EXTENSION") Then
58+
ConsoleWrite("!> Error: Failed to load extension." & @CRLF)
59+
EndIf
60+
EndSwitch
61+
EndFunc
62+
```
63+
64+
#### Key Features in v1.3.0:
65+
66+
- **Isolation**: Loading an extension in `Web1` does not affect `Web2`. Each instance stays completely independent.
67+
68+
- **Persistence**: Since v1.3.0 uses dedicated User Profiles, extension settings (like custom filters or dark mode intensity) are saved automatically in the profile folder.
69+
70+
- **Event Tracking**: The new version sends a `EXTENSION_LOADED` message back to AutoIt so you can confirm the injection was successful.
71+
72+
73+
---
74+
75+
### Manual Method: Extracting Extensions from your Browser
76+
77+
If you already have the extension installed in your Chrome or Edge browser, follow these steps to "extract" it for use with this library:
78+
79+
1. **Find the Extension ID:**
80+
81+
- Open your browser and navigate to `chrome://extensions/` or `edge://extensions/`.
82+
83+
- Enable **Developer mode** (toggle switch at the top right).
84+
85+
- Locate your extension (e.g., Dark Reader) and copy its **ID** (a long string of random letters like `eimadpbcbfnmbkopoojfekhnkhdbieeh`).
86+
87+
2. **Locate the Source Folder:**
88+
89+
- Press `Win + R`, paste the following path, and press Enter:
90+
91+
- **For Edge:** `%LocalAppData%\Microsoft\Edge\User Data\Default\Extensions`
92+
93+
- **For Chrome:** `%LocalAppData%\Google\Chrome\User Data\Default\Extensions`
94+
95+
- Find the folder named after the **ID** you copied in Step 1.
96+
97+
3. **Identify the Unpacked Folder:**
98+
99+
- Inside that folder, you will see a sub-folder named after the version number (e.g., `4.9.118_0`).
100+
101+
- **Crucial:** This version folder is your "Unpacked Extension". It contains the `manifest.json` file.
102+
103+
4. **Copy to your Project:**
104+
105+
- Copy the version folder into your project's `Extensions_Lib` directory.
106+
107+
- **Pro Tip:** Rename the folder from `4.9.118_0` to something readable like `DarkReader` to keep your code clean.
108+
109+
110+
---
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
A powerful bridge that allows **AutoIt** to use the modern **Microsoft Edge WebView2** (Chromium) engine via a C# COM wrapper. This project enables you to render modern HTML5, CSS3, and JavaScript directly inside your AutoIt applications with a 100% event-driven architecture.
2+
3+
---
4+
5+
## 1. WebViewManager (`NetWebView2.Manager`)
6+
7+
### **Lifecycle & Core State**
8+
9+
|**Method**|**Description**|
10+
|---|---|
11+
|**`.Initialize(parentHandle, userDataFolder, x, y, width, height)`**|Initializes the WebView2.<br><br> <br><br>_Note: Uses default values (0) for coordinates/size if not specified._|
12+
|**`.IsReady()`**|Returns `True` if the WebView2 environment is fully initialized.|
13+
|**`.Cleanup()`**|Releases all resources and closes the browser engine.|
14+
|**`.GetBridge()`**|Returns the `IBridgeActions` object for AutoIt/JS communication.|
15+
16+
### **Navigation & Document**
17+
18+
|**Method**|**Description**|
19+
|---|---|
20+
|**`.Navigate(url)`**|Navigates to the specified URL.|
21+
|**`.NavigateToString(html)`**|Loads raw HTML content.|
22+
|**`.Reload()`**|Refreshes the current page.|
23+
|**`.Stop()`**|Stops the current loading process.|
24+
|**`.GoBack()`**|Navigates backward in history.|
25+
|**`.GoForward()`**|Navigates forward in history.|
26+
|**`.GetSource()`**|Returns the current URL as a string.|
27+
|**`.GetDocumentTitle()`**|Returns the title of the current document.|
28+
|**`.GetHtmlSource()`**|Triggers a request to retrieve the full HTML source.|
29+
|**`.GetSelectedText()`**|Retrieves currently selected text from the page.|
30+
31+
### **UI & Layout**
32+
33+
|**Method**|**Description**|
34+
|---|---|
35+
|**`.Resize(width, height)`**|Updates the dimensions of the WebView control.|
36+
|**`.SetZoom(factor)`**|Sets the zoom factor (e.g., `1.5` for 150%).|
37+
|**`.ResetZoom()`**|Resets zoom to the default level.|
38+
|**`.SetStatusBarEnabled(bool)`**|Shows/hides the browser status bar.|
39+
|**`.SetContextMenuEnabled(bool)`**|Enables/disables the right-click context menu.|
40+
|**`.SetMuted(bool)`**|Mutes or unmutes all browser audio.|
41+
|**`.IsMuted()`**|Returns the current mute state (`Boolean`).|
42+
|**`.SetUserAgent(string)`**|Sets a custom User Agent string.|
43+
44+
### **Security & Restrictions**
45+
46+
|**Method**|**Description**|
47+
|---|---|
48+
|**`.LockWebView()`**|High-level method to lock down the browser UI and features.|
49+
|**`.DisableBrowserFeatures()`**|Disables specific built-in browser functionalities.|
50+
|**`.SetScriptEnabled(bool)`**|Enables or disables JavaScript execution.|
51+
|**`.SetWebMessageEnabled(bool)`**|Enables or disables Web Message communication.|
52+
53+
### **Scripting & CSS**
54+
55+
|**Method**|**Description**|
56+
|---|---|
57+
|**`.ExecuteScript(script)`**|Runs a JavaScript string in the page context.|
58+
|**`.InjectCss(cssCode)`**|Injects custom CSS styles into the page.|
59+
|**`.ClearInjectedCss()`**|Removes all previously injected CSS.|
60+
|**`.ToggleAuditHighlights(bool)`**|Toggles visual audit highlights for debugging.|
61+
62+
### **Content Filtering (AdBlock)**
63+
64+
|**Method**|**Description**|
65+
|---|---|
66+
|**`.SetAdBlock(active)`**|Enables or disables the AdBlocker interceptor.|
67+
|**`.AddBlockRule(domain)`**|Adds a specific domain or pattern to the block list.|
68+
|**`.ClearBlockRules()`**|Removes all active blocking rules.|
69+
70+
### **Advanced Features**
71+
72+
|**Method**|**Description**|
73+
|---|---|
74+
|**`.CapturePreview(path, format)`**|Saves a screenshot (`"png"` or `"jpg"`).|
75+
|**`.ExportToPdf(path)`**|Saves the current page as a PDF file.|
76+
|**`.Print()`**|Opens the standard system print dialog.|
77+
|**`.ShowPrintUI()`**|Shows the WebView2-specific print interface.|
78+
|**`.AddExtension(path)`**|Loads a Chromium extension from the specified folder.|
79+
|**`.CallDevToolsProtocolMethod(method, json)`**|Directly calls a CDP method.|
80+
|**`.ClearBrowserData()`**|Wipes history, cache, and other browsing data.|
81+
82+
### **Cookie Management**
83+
84+
|**Method**|**Description**|
85+
|---|---|
86+
|**`.GetCookies(channelId)`**|Starts an async request to fetch cookies (result via events).|
87+
|**`.AddCookie(name, val, dom, path)`**|Adds or updates a cookie.|
88+
|**`.DeleteCookie(name, dom, path)`**|Deletes a specific cookie.|
89+
|**`.DeleteAllCookies()`**|Clears all cookies from the session.|
90+
91+
### **Internal JSON Support**
92+
93+
|**Method**|**Description**|
94+
|---|---|
95+
|**`.ParseJsonToInternal(json)`**|Parses a JSON string into the Manager's internal storage.|
96+
|**`.GetInternalJsonValue(path)`**|Retrieves a value from the internal JSON storage by path.|
97+
98+
---
99+
100+
## 2. JsonParser (`NetJson.Parser`)
101+
102+
### **Methods**
103+
104+
| **Method** | **Description** |
105+
| --------------------------------- | ------------------------------------------------- |
106+
| **`.Parse(jsonString)`** | Parses a raw JSON string. |
107+
| **`.LoadFromFile(path)`** | Loads JSON from a text file. |
108+
| **`.SaveToFile(path)`** | Writes current JSON back to a file. |
109+
| **`.GetTokenValue(path)`** | Gets a value using path notation (`"root.node"`). |
110+
| **`.SetTokenValue(path, value)`** | Updates or adds a value at a specific path. |
111+
| **`.Exists(path)`** | Checks if a path exists (Returns Boolean). |
112+
| **`.GetArrayCount()`** | Returns the number of items in a JSON array. |
113+
| **`.GetPrettyJson()`** | Returns formatted JSON. |
114+
| **`.GetMinifiedJson()`** | Returns compact JSON. |
115+
| **`.EscapeString(text)`** | Escapes a string for JSON safety. |
116+
| **`.UnescapeString(text)`** | Reverts JSON-escaped text. |
117+
| **`.Clear()`** | Resets the parser state. |
118+
119+
---
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
**Current Version:** 1.3.0 (2025-12-25)
2+
3+
---
4+
5+
## Version 1.3.0 - (2025-12-25)
6+
7+
### Added
8+
9+
- **Multi-Instance Support**: Added the ability to create and manage multiple independent WebView2 instances within the same AutoIt application.
10+
11+
- **Extension Support**: Introduced the `AddExtension` method, allowing the loading of unpacked browser extensions (Manifest V2 and V3) per instance.
12+
13+
- **Independent User Profiles**: Each instance now supports a unique `UserDataFolder`, enabling isolated cookies, cache, and browser history (e.g., `Profile_1`, `Profile_2`).
14+
15+
- **Context Menu Control**: Added `SetContextMenuEnabled` to programmatically enable or disable the right-click menu.
16+
17+
- **DevTools Management**: Added `SetDevToolsEnabled` to toggle access to the browser's developer tools.
18+
19+
20+
### Fixed
21+
22+
- **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_`).
23+
24+
- **Resource Locking**: Improved the `Cleanup()` method to ensure all WebView2 processes and profile files are properly released upon closing.
25+
26+
- **Initialization Sequence**: Fixed a race condition where calling methods before the engine was fully ready caused crashes; events now properly wait for the `INIT_READY` signal.
27+
28+
29+
### Changed
30+
31+
- **Event-Driven Architecture**: Refactored the communication layer to be 100% event-driven, eliminating the need for `Sleep()` or polling loops.
32+
33+
- **Bridge Logic**: Optimized the `.NET` to `AutoIt` bridge to handle high-frequency messaging without UI blocking.
34+
35+
- **Resizing Logic**: Updated the recommended implementation to use `WM_SIZE` for smoother synchronization between AutoIt GUI containers and the WebView2 engine.
36+
37+
38+
- ---
39+
## Version 1.2.0 - 2024-11-15
40+
41+
### Added
42+
43+
- **JavaScript Bridge**: Initial implementation of `postMessage` communication from JavaScript to AutoIt.
44+
45+
- **ExecuteScript Method**: Added ability to run custom JS code from AutoIt directly into the WebView.
46+
47+
- **Navigation Events**: Introduced `NAV_STARTING` and `NAV_COMPLETED` events for better page load tracking.
48+
49+
50+
### Changed
51+
52+
- **DLL Optimization**: Migrated core logic to a dedicated .NET DLL to handle complex COM interop.
53+
54+
- **Stability**: Improved memory management when reloading large websites.
55+
56+
57+
---
58+
59+
## Version 1.1.0 - 2024-09-10
60+
61+
### Added
62+
63+
- **Custom Profile Path**: Introduced the ability to set a custom `UserDataFolder` for basic data persistence.
64+
65+
- **UserAgent Override**: Added method to change the browser's User-Agent string.
66+
67+
- **Zoom Factor**: Added support for manual zoom control (`SetZoomFactor`).
68+
69+
70+
### Fixed
71+
72+
- **Object Cleanup**: Fixed a bug where `msedgewebview2.exe` processes remained active after AutoIt script exited.
73+
74+
75+
---
76+
77+
## Version 1.0.0 - 2024-06-20 (Initial Release)
78+
79+
### Added
80+
81+
- **Core Engine**: Basic integration of WebView2 control into AutoIt GUI via COM.
82+
83+
- **Basic Navigation**: Implemented `Maps` and `MapsToString` methods.
84+
85+
- **Resize Support**: Fundamental resizing of the browser window relative to the parent GUI.
86+
87+
---
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
---
3+
4+
1. Finding Elements (Selectors)
5+
6+
| **Command** | **Description** |
7+
| ---------------------------------- | ----------------------------------------------------- |
8+
| `document.querySelector('.class')` | Finds the **first** element with this specific class. |
9+
| `document.querySelectorAll('a')` | Finds **all** links (returns a list/collection). |
10+
| `element.parentElement` | Moves one level up to the element's "parent". |
11+
12+
2. Extracting Text & Content
13+
14+
| **Command** | **Description** |
15+
| ------------------------------ | ---------------------------------------------- |
16+
| `element.innerText` | Gets only the visible, clean text. |
17+
| `element.innerHTML` | Gets the entire HTML code inside the element. |
18+
| `element.getAttribute('href')` | Retrieves the URL address of a link. |
19+
| `element.value` | Retrieves text from an Input Box or Textarea. |
20+
21+
3. Data Cleaning (Strings)
22+
23+
| **Command** | **Description** |
24+
| -------------------- | ----------------------------------------------------------------------------- |
25+
| `.trim()` | Removes whitespace from start and end (Similar to `StringStripWS` in AutoIt). |
26+
| `.replace('A', 'B')` | Replaces text (Similar to `StringReplace`). |
27+
| `.split('\n')` | Splits text into an array based on new lines. |
28+
29+
4. Communication with AutoIt
30+
31+
| **Command** | **Description** |
32+
| ----------------------------------------- | ---------------------------------------------------------------------- |
33+
| `window.chrome.webview.postMessage(data)` | **The most important:** Sends the `data` to the AutoIt Event handler. |
34+
35+
---
36+
37+
💡 The "Magic" Snippet for Table Scraping
38+
39+
If you find a table and want to extract all its data, use this code as your primary template:
40+
41+
JavaScript
42+
43+
```
44+
//
45+
var results = [];
46+
// 1. Find all rows
47+
var rows = document.querySelectorAll('table tr');
48+
49+
rows.forEach(row => {
50+
// 2. Find cells for each row
51+
var cells = row.querySelectorAll('td');
52+
53+
if (cells.length > 0) {
54+
// 3. Format the data structure (e.g., Column1 | Column2)
55+
var line = cells[0].innerText.trim() + " | " + cells[1].innerText.trim();
56+
results.push(line);
57+
}
58+
});
59+
60+
// 4. Send everything back to AutoIt
61+
window.chrome.webview.postMessage(results.join('\n'));
62+
```
63+

0 commit comments

Comments
 (0)