### CustomScheme Usage Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/types.md Demonstrates how to instantiate and configure a CustomScheme object for use during CefRuntime initialization. This example registers a custom scheme named 'app'. ```csharp var customScheme = new CustomScheme { SchemeName = "app", DomainName = "", IsStandard = true, IsSecure = true, IsCorsEnabled = true, SchemeHandlerFactory = new AppSchemeHandlerFactory() }; CefRuntimeLoader.Initialize(null, null, new[] { customScheme }); ``` -------------------------------- ### Handlers Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Provides examples of how to customize browser behavior by implementing and assigning various handlers, such as ContextMenuHandler, DialogHandler, DownloadHandler, and JSDialogHandler. ```APIDOC ## Handlers Example ### Customize Context Menu Allows modification of the browser's context menu. You can clear existing items and add custom ones. ```csharp _browser.ContextMenuHandler = new ContextMenuHandler { OnBeforeContextMenu = (browser, frame, state, model) => { // Remove all menu items model.Clear(); // Add custom items model.AddItem(1, "Copy"); model.AddItem(2, "Paste"); } }; ``` ### Handle File Dialogs Assign a custom handler to manage file selection dialogs. ```csharp _browser.DialogHandler = new CustomDialogHandler(); ``` ### Handle Downloads Assign a custom handler to manage file download events. ```csharp _browser.DownloadHandler = new CustomDownloadHandler(); ``` ### Handle JavaScript Dialogs Assign a custom handler to manage JavaScript-initiated dialogs (e.g., alert, confirm, prompt). ```csharp _browser.JSDialogHandler = new CustomJSDialogHandler(); ``` ``` -------------------------------- ### Basic CefRuntimeLoader Initialization Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Initializes the CEF runtime with default settings. This is the simplest way to start the CEF runtime. ```csharp CefRuntimeLoader.Initialize(); ``` -------------------------------- ### LoadStart Event Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Fired when the browser starts loading a frame. Useful for tracking navigation progress. ```APIDOC ## LoadStart Event ### Description Fired when the browser starts loading a frame. ### Event Signature ```csharp public event LoadStartEventHandler LoadStart ``` ### Event Args `LoadStartEventArgs` ``` -------------------------------- ### Handle Load Start Event Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Captures the event when a frame starts loading a new URL. This can be used to track navigation progress or modify requests before they are sent. ```csharp browser.LoadStart += (sender, args) => { // Handle load start }; ``` -------------------------------- ### Async Method Support Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/ObjectBinding.md Demonstrates how .NET methods returning Task or Task can be awaited in JavaScript. Ensure the method is marked as 'async'. ```csharp public class HostAPI { public async Task FetchDataAsync(int id) { await Task.Delay(100); return $"Data for {id}"; } } var api = new HostAPI(); browser.RegisterJavascriptObject(api, "api"); // JavaScript: // api.fetchDataAsync(42).then(result => console.log(result)); ``` -------------------------------- ### Complete BaseCefBrowser Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Demonstrates the initialization of CEF, creation of an AvaloniaCefBrowser instance, event handling for load states and console messages, JavaScript evaluation and execution, object registration, and navigation. ```csharp using Xilium.CefGlue.Common; using Xilium.CefGlue.Avalonia; // Initialize CEF CefRuntimeLoader.Initialize(); // Create browser var browser = new AvaloniaCefBrowser(); // Handle events browser.BrowserInitialized += () => { browser.Address = "https://example.com"; }; browser.LoadStart += (args) => { statusLabel.Content = "Loading..."; }; browser.LoadEnd += (args) => { statusLabel.Content = $"Loaded {args.HttpStatusCode}"; }; browser.ConsoleMessage += (args) => { Debug.WriteLine($"[{args.Level}] {args.Message}"); }; // Evaluate JavaScript var title = await browser.EvaluateJavaScript("document.title"); // Execute JavaScript browser.ExecuteJavaScript("console.log('Page loaded');"); // Register .NET object var api = new NativeAPI(); browser.RegisterJavascriptObject(api, "api"); // Navigate browser.Address = "https://example.com"; ``` -------------------------------- ### Initialize CefRuntimeLoader with CefSettings Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/configuration.md Configure CefGlue browser runtime settings, including cache paths, user agent, rendering mode, and logging. This example demonstrates setting up essential properties before initializing the CefRuntimeLoader. ```csharp var settings = new CefSettings { CachePath = "/path/to/cache", UserDataPath = "/path/to/userdata", UserAgentString = "MyApp/1.0", WindowlessRenderingEnabled = false, MultiThreadedMessageLoop = true, // Windows NoSandbox = false, LogFile = "/path/to/log.txt", LogSeverity = CefLogSeverity.Info }; CefRuntimeLoader.Initialize(settings); ``` -------------------------------- ### C++ Handler OnQuery Implementation Example Source: https://github.com/outsystems/cefglue/blob/main/CefGlue/Wrapper/MessageRouter/ReadMe.txt Handle a query received in the browser process. This C++ code demonstrates how to process a request and send a response back. ```cpp void MyHandler::OnQuery(int64 query_id, CefRefPtr browser, CefRefPtr frame, const CefString& request, bool persistent, CefRefPtr callback) { if (request == "my_request") { callback->Continue("my_response"); return true; } return false; // Not handled. } ``` -------------------------------- ### Example: ExecuteMethod with JSON Arguments Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/ObjectBinding.md Demonstrates how to wrap a .NET object and execute its method using JSON-serialized arguments. The callback logs the result or any errors. ```csharp public class HostAPI { public int Add(int a, int b) => a + b; } var nativeObj = new NativeObject("api", new HostAPI()); // Execute with JSON nativeObj.ExecuteMethod("add", "[5, 3]", (result, error) => { if (error != null) Debug.WriteLine($"Error: {error.Message}"); else Debug.WriteLine($"Result: {result}"); // 8 }); ``` -------------------------------- ### Customize Context Menu and Handle Downloads Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Provides examples for customizing the browser's context menu and handling file downloads. Implement OnBeforeContextMenu to modify menu items and OnBeforeDownload to specify download paths. ```csharp // Customize context menu browser.ContextMenuHandler = new ContextMenuHandler { OnBeforeContextMenu = (browser, frame, state, model) => { model.Clear(); model.AddItem(1, "Back"); model.AddItem(2, "Reload"); } }; // Handle downloads browser.DownloadHandler = new DownloadHandler { OnBeforeDownload = (browser, item, name, callback) => { var path = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Downloads), name); callback.Continue(path, showDialog: false); } }; ``` -------------------------------- ### BrowserInitialized Event Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Fired when the browser has been initialized and is ready for use. This is a common event to subscribe to for initial setup tasks. ```APIDOC ## BrowserInitialized Event ### Description Fired when the browser has been initialized and is ready for use. ### Event Signature ```csharp public event Action BrowserInitialized ``` ### Example ```csharp browser.BrowserInitialized += () => { browser.Address = "https://example.com"; }; ``` ``` -------------------------------- ### C# KeyboardHandler Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Example of a custom KeyboardHandler that intercepts F5 for reload and Ctrl+P for printing. Assign this handler to browser.KeyboardHandler. ```csharp public class CustomKeyboardHandler : KeyboardHandler { protected override bool OnPreKeyEvent(CefBrowser browser, CefKeyEvent keyEvent) { // Intercept F5 (reload) if (keyEvent.WindowsKeyCode == 0x74) // F5 { browser.Reload(); return true; // Suppress default } // Intercept Ctrl+P (print) if (keyEvent.WindowsKeyCode == 0x50 && (keyEvent.Modifiers & CefEventFlags.ControlDown) != 0) { browser.Print(); return true; } return false; } } browser.KeyboardHandler = new CustomKeyboardHandler(); ``` -------------------------------- ### Set and Get Browser Address Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Demonstrates how to set the current URL to navigate the browser and how to retrieve the current URL. ```csharp browser.Address = "https://example.com"; string currentUrl = browser.Address; ``` -------------------------------- ### Settings Property Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Gets the initial browser settings. Changes to this property after browser initialization have no effect. ```APIDOC ## Settings Property ### Description Gets the initial browser settings. Changes to this property after browser initialization have no effect. ### Type CefBrowserSettings ### Remarks Configure settings before the browser is displayed. Settings include security policies, cache behavior, and rendering options. ``` -------------------------------- ### JavaScript Query Execution Example Source: https://github.com/outsystems/cefglue/blob/main/CefGlue/Wrapper/MessageRouter/ReadMe.txt Execute a query from JavaScript to the browser process. The query can be persistent and includes callbacks for success and failure. ```javascript window.cefQuery({request: 'my_request', persistent: false, onSuccess: function(response) { print(response); }, onFailure: function(error_code, error_message) {} }); ``` -------------------------------- ### WpfCefBrowser API Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Documentation for the WPF browser control, including XAML and code-behind examples, event handling, and JavaScript integration. ```APIDOC ## WpfCefBrowser ### Description Implementation of the browser control for WPF applications. ### Constructor - **WpfCefBrowser()**: Initializes a new instance of the WpfCefBrowser class. ### Usage - **XAML**: Examples of XAML markup for navigation controls. - **Code-behind**: Complete code-behind examples. ### Features - Event handler integration. - JavaScript evaluation examples. - Object binding examples. - Custom handler examples. - Application initialization pattern. - Zoom control examples. - Disposal and cleanup procedures. ``` -------------------------------- ### LoadStartEventHandler Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/types.md Delegate for handling the start of a page load. It is invoked when a new page navigation begins. ```APIDOC ## LoadStartEventHandler ### Description Delegate for handling the start of a page load. It is invoked when a new page navigation begins. ### Signature `public delegate void LoadStartEventHandler(LoadStartEventArgs args);` ``` -------------------------------- ### LoadStartEventArgs Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/types.md Represents event arguments for when a page starts loading. It contains information about the frame that is initiating the load. ```APIDOC ## LoadStartEventArgs ### Description Provides data for the `LoadStart` event, indicating that a web page has begun loading. ### Properties - **Frame** (CefFrame) - Required - The frame that is loading. ``` -------------------------------- ### Handlers API Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Comprehensive documentation for all 13 handler types, detailing their methods, parameters, and usage examples for customization. ```APIDOC ## Handlers ### Description Documentation for all handler interfaces used for customizing CEFGLUE behavior. ### Handler Types (13 total) - BrowserProcessHandler - ContextMenuHandler - DialogHandler - DisplayHandler - DownloadHandler - DragHandler - FindHandler - FocusHandler - KeyboardHandler - LifeSpanHandler - RenderHandler - JSDialogHandler - RequestHandler ### Content for each handler - Complete method signatures. - Usage examples. - Parameter descriptions. - Purpose of each customization point. ``` -------------------------------- ### Good vs. Ambiguous Method Naming Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/ObjectBinding.md Choose clear and descriptive method names for your API. Avoid ambiguous names like 'Get' which can be unclear in intent. ```csharp public class API { public string GetUsername() { } // Good public string GetUser() { } // Also good public string Get() { } // Ambiguous } ``` -------------------------------- ### Errors Reference Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/INDEX.md Comprehensive guide to error handling, recovery patterns, and troubleshooting within CEFGlue. ```APIDOC ## Errors Reference ### Description This section provides a detailed guide to error handling, recovery strategies, and troubleshooting for common issues encountered when using the CEFGlue library. ### Error Categories - **Initialization Errors**: Covers issues like missing subprocesses or resources required for CEF startup. - **JavaScript Evaluation Errors**: Addresses problems during script execution, including timeouts, deserialization failures, and runtime errors. - **Object Binding Errors**: Details errors related to unknown methods or failures in binding .NET objects to JavaScript. - **Browser Lifecycle Errors**: Information on errors occurring during the browser's operational phases. - **Load Error Codes**: Explains over 20 `CefErrorCode` values and how to handle them. - **Unhandled Exceptions**: Patterns for managing and reporting unhandled exceptions in both the main and render processes. - **Console Errors**: Guidance on capturing and handling errors reported in the browser's console. ### Recovery and Troubleshooting - **Recovery Patterns**: Provides examples of how to implement robust error recovery mechanisms. - **Safe Wrapper Examples**: Demonstrates how to create safe wrappers around potentially error-prone operations. - **Troubleshooting Guide**: Offers a systematic approach to diagnosing and resolving common problems. ``` -------------------------------- ### Customize Context Menu Handler Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Provides an example of customizing the browser's context menu by clearing default items and adding custom ones using the `ContextMenuHandler`. ```csharp // Customize context menu _browser.ContextMenuHandler = new ContextMenuHandler { OnBeforeContextMenu = (browser, frame, state, model) => { // Remove all menu items model.Clear(); // Add custom items model.AddItem(1, "Copy"); model.AddItem(2, "Paste"); } }; ``` -------------------------------- ### Implement Custom Dialog Handling Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Override the OnFileDialog method to provide custom logic for file open/save dialogs. This example uses system dialogs and continues the callback with the selected file name. ```csharp public class CustomDialogHandler : DialogHandler { protected override bool OnFileDialog( CefBrowser browser, CefDialogType mode, string title, string defaultPath, string[] acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback) { // Use system file dialog if (mode == CefDialogType.Open) { var dialog = new OpenFileDialog { Title = title }; if (dialog.ShowDialog() == true) { callback.Continue(new[] { dialog.FileName }); } } else if (mode == CefDialogType.Save) { var dialog = new SaveFileDialog { Title = title }; if (dialog.ShowDialog() == true) { callback.Continue(new[] { dialog.FileName }); } } return true; } } browser.DialogHandler = new CustomDialogHandler(); ``` -------------------------------- ### Custom Context Menu Handler Example Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Implement a custom context menu handler by overriding OnBeforeContextMenu to modify menu items and OnContextMenuCommand to handle user selections. Assign the custom handler to the browser's ContextMenuHandler property. ```csharp public class CustomContextMenuHandler : ContextMenuHandler { protected override void OnBeforeContextMenu( CefBrowser browser, CefFrame frame, CefContextMenuParams state, CefMenuModel model) { // Remove all default items model.Clear(); // Add custom items model.AddItem(1, "Back"); model.AddItem(2, "Forward"); model.AddItem(3, "Reload"); model.AddSeparator(); model.AddItem(4, "Developer Tools"); } protected override bool OnContextMenuCommand( CefBrowser browser, CefFrame frame, CefContextMenuParams state, int commandId, CefEventFlags eventFlags) { switch (commandId) { case 1: if (browser.CanGoBack) browser.GoBack(); return true; case 2: if (browser.CanGoForward) browser.GoForward(); return true; case 3: browser.Reload(); return true; case 4: browser.ShowDeveloperTools(); return true; } return false; } } // Assign to browser browser.ContextMenuHandler = new CustomContextMenuHandler(); ``` -------------------------------- ### Initializing Browser Address After Initialization Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/errors.md Shows the correct way to set the browser's address by waiting for the `BrowserInitialized` event to ensure the browser is ready. ```csharp var browser = new AvaloniaCefBrowser(); // Wrong: Browser not initialized yet // browser.Address = "https://example.com"; // May not work // Right: Wait for initialization browser.BrowserInitialized += () => { browser.Address = "https://example.com"; }; ``` -------------------------------- ### Define LoadStartEventHandler Delegate Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/types.md Defines a delegate for handling the start of a page load. It accepts LoadStartEventArgs. ```csharp public delegate void LoadStartEventHandler(LoadStartEventArgs args); ``` -------------------------------- ### ZoomLevel Property Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Gets or sets the zoom level. The default zoom level is 0.0 (100%). ```APIDOC ## ZoomLevel Property ### Description Gets or sets the zoom level. The default zoom level is 0.0 (100%). ### Type double ### Example ```csharp browser.ZoomLevel = 0.5; // 50% zoom browser.ZoomLevel = 1.0; // 200% zoom ``` ``` -------------------------------- ### Initialize CEF Glue Runtime Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/configuration.md This snippet shows how to initialize the CEF Glue runtime with custom settings, command-line flags, and custom URL schemes. Ensure all necessary paths and configurations are correctly set before calling Initialize. ```csharp using Xilium.CefGlue.Common; using Xilium.CefGlue.Common.Shared; public class App { public static void InitializeCef() { // Create settings var settings = new CefSettings { // Cache and storage CachePath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp", "Cache"), UserDataPath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp"), // UI UserAgentString = "MyApp/1.0", LogFile = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp", "Debug.log"), LogSeverity = CefLogSeverity.Info, // Platform-specific WindowlessRenderingEnabled = false, NoSandbox = false, MultiThreadedMessageLoop = true // Windows }; // Command-line flags var flags = new[] { KeyValuePair.Create("disable-features", "FirstPartySets"), KeyValuePair.Create("no-first-run", "") }; // Custom schemes var customSchemes = new[] { new CustomScheme { SchemeName = "app", DomainName = "", IsStandard = true, IsSecure = true, SchemeHandlerFactory = new AppSchemeHandlerFactory() } }; // Initialize CefRuntimeLoader.Initialize(settings, flags, customSchemes); } } ``` -------------------------------- ### Create Browser Instance Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Instantiate a browser control for either Avalonia or WPF applications. ```csharp // Avalonia var browser = new AvaloniaCefBrowser(); // or WPF var browser = new WpfCefBrowser(); ``` -------------------------------- ### WpfCefBrowser API Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/INDEX.md Implementation of CefBrowser for WPF applications, offering comprehensive examples for integration and event handling. ```APIDOC ## WpfCefBrowser API ### Description Provides an implementation of `CefBrowser` tailored for WPF applications. This class enables embedding CEF browser controls within WPF UIs, with extensive examples covering initialization, XAML markup, code-behind logic, event handling, and JavaScript interop. ### Initialization Details on constructors and the necessary steps for initializing the browser component. ### Usage - **XAML Markup**: Examples showcasing how to declare and configure `WpfCefBrowser` in XAML. - **Code-behind Example**: A complete example demonstrating how to interact with the browser instance from C# code, including handling all available events. - **JavaScript Evaluation and Interop**: Examples for executing JavaScript and enabling communication between JavaScript and .NET. - **Object Binding**: Demonstrations of how to bind .NET objects to the JavaScript environment. - **Custom Handler Integration**: Guidance on integrating custom handlers for advanced customization. ### Application Initialization Pattern Illustrates a recommended pattern for initializing the browser within a WPF application lifecycle. ### Platform This implementation is specific to the Windows platform. ``` -------------------------------- ### Address Property Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Gets or sets the current URL of the browser. Setting this property navigates to the specified URL. ```APIDOC ## Address Property ### Description Gets or sets the current URL. Setting this property navigates to the specified URL. ### Type string ### Example ```csharp browser.Address = "https://example.com"; string currentUrl = browser.Address; ``` ``` -------------------------------- ### CefRuntimeLoader Initialization with Custom Settings Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Initializes the CEF runtime using custom CefSettings, such as cache path and user agent. Ensure the cache path is valid for your environment. ```csharp var settings = new CefSettings { CachePath = "/path/to/cache", UserAgentString = "MyApp/1.0" }; CefRuntimeLoader.Initialize(settings); ``` -------------------------------- ### CefRuntimeLoader.Initialize Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Initializes the CEF runtime with optional settings, command-line flags, and custom URL schemes. This method must be called before creating any browser instances. The initialization is deferred until the first browser is created. ```APIDOC ## Initialize ### Description Initializes the CEF runtime with optional settings, command-line flags, and custom URL schemes. This method must be called before creating any browser instances. The initialization is deferred until the first browser is created. ### Method ```csharp public static void Initialize( CefSettings settings = null, KeyValuePair[] flags = null, CustomScheme[] customSchemes = null ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | settings | CefSettings | No | null | Browser settings (window mode, rendering, cache paths, etc.). If null, defaults are used. | | flags | KeyValuePair[] | No | null | CEF command-line flags (e.g., `disable-features`, `enable-features`). | | customSchemes | CustomScheme[] | No | null | Custom URL schemes to register (e.g., `app://`, `data://`). | ### Request Example ```csharp // Basic initialization CefRuntimeLoader.Initialize(); // With custom settings var settings = new CefSettings { CachePath = "/path/to/cache", UserAgentString = "MyApp/1.0" }; CefRuntimeLoader.Initialize(settings); // With command-line flags var flags = new[] { KeyValuePair.Create("disable-features", "FirstPartySets"), KeyValuePair.Create("enable-features", "MyFeature") }; CefRuntimeLoader.Initialize(null, flags); // With custom schemes var customSchemes = new[] { new CustomScheme { SchemeName = "app", DomainName = "", IsStandard = true, IsSecure = true, SchemeHandlerFactory = new AppSchemeHandlerFactory() } }; CefRuntimeLoader.Initialize(null, null, customSchemes); ``` ### Response #### Success Response void #### Response Example None ``` -------------------------------- ### Registering and Calling JavaScript Object Methods Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/errors.md Demonstrates registering a .NET object with JavaScript and the difference between calling an existing method and a non-existent one. ```csharp public class API { public void ExistingMethod() { } } var api = new API(); browser.RegisterJavascriptObject(api, "api"); // JavaScript calls: // api.existingMethod() // OK // api.nonExistentMethod() // Throws exception ``` -------------------------------- ### Execute and Evaluate JavaScript Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Demonstrates how to execute arbitrary JavaScript code and evaluate JavaScript expressions to retrieve data from the browser context. ```csharp // Execute JavaScript _browser.ExecuteJavaScript("alert('Hello from .NET!');"); // Evaluate JavaScript var title = await _browser.EvaluateJavaScript("document.title"); var url = await _browser.EvaluateJavaScript("window.location.href"); ``` -------------------------------- ### CefRuntimeLoader Initialization with Command-Line Flags Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Initializes the CEF runtime with specific command-line flags to enable or disable certain CEF features. Use this to fine-tune CEF behavior. ```csharp var flags = new[] { KeyValuePair.Create("disable-features", "FirstPartySets"), KeyValuePair.Create("enable-features", "MyFeature") }; CefRuntimeLoader.Initialize(null, flags); ``` -------------------------------- ### Set and Get Browser Zoom Level Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Shows how to adjust the zoom level of the browser view. The default is 0.0 (100%). ```csharp browser.ZoomLevel = 0.5; // 50% zoom browser.ZoomLevel = 1.0; // 200% zoom ``` -------------------------------- ### Initialize CEF Runtime Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Call this once at application startup to initialize the CEF runtime. ```csharp using Xilium.CefGlue.Common; // Call once at application startup CefRuntimeLoader.Initialize(); ``` -------------------------------- ### JavaScript Interop Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Demonstrates how to execute and evaluate JavaScript within the browser, and how to register .NET objects for interop with JavaScript. ```APIDOC ## JavaScript Interop ### Execute JavaScript Executes a JavaScript string in the browser's main frame. ```csharp _browser.ExecuteJavaScript("alert('Hello from .NET!');"); ``` ### Evaluate JavaScript Evaluates a JavaScript expression and returns the result, optionally casting it to a specified type. ```csharp // Evaluate JavaScript and get the document title var title = await _browser.EvaluateJavaScript("document.title"); // Evaluate JavaScript and get the current URL var url = await _browser.EvaluateJavaScript("window.location.href"); ``` ### Register .NET Object for JavaScript Registers a .NET object instance that can be accessed from JavaScript. Methods and properties of the registered object can be invoked from the browser's JavaScript context. **HostAPI Class Example:** ```csharp public class HostAPI { public string GetAppName() => "MyApp"; public void ShowNotification(string message) => ShowAlert(message); } ``` **Registration:** ```csharp var api = new HostAPI(); _browser.RegisterJavascriptObject(api, "hostAPI"); ``` **JavaScript Usage:** ```javascript // Call a method to get the app name hostAPI.getAppName(); // Call a method to show a notification hostAPI.showNotification("Hello!"); ``` ``` -------------------------------- ### Evaluate JavaScript and Get Result Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Evaluates a JavaScript expression asynchronously and deserializes the JSON result to the specified type T. Handles timeouts. ```csharp // Get a simple value var title = await browser.EvaluateJavaScript("document.title"); ``` ```csharp // Get an object var location = await browser.EvaluateJavaScript( @"({ href: window.location.href, pathname: window.location.pathname, hostname: window.location.hostname })") ``` ```csharp // With timeout var result = await browser.EvaluateJavaScript( "heavyComputation()", timeout: TimeSpan.FromSeconds(5) ); ``` ```csharp public class LocationData { public string href { get; set; } public string pathname { get; set; } public string hostname { get; set; } } ``` -------------------------------- ### Custom JSDialogHandler Implementation Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Implement a custom JSDialogHandler to control how JavaScript dialogs are displayed and handled. This example shows how to manage alert, confirm, and prompt dialogs. ```csharp public class CustomJSDialogHandler : JSDialogHandler { protected override bool OnJSDialog( CefBrowser browser, string originUrl, CefJSDialogType dialogType, string messageText, string defaultPromptText, IJSDialogCallback callback) { switch (dialogType) { case CefJSDialogType.Alert: MessageBox.Show(messageText, "Alert"); callback.Continue(true, ""); return true; case CefJSDialogType.Confirm: bool result = MessageBox.Show(messageText, "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes; callback.Continue(result, ""); return true; case CefJSDialogType.Prompt: // Custom prompt dialog string input = PromptDialog.Show(messageText, defaultPromptText); callback.Continue(input != null, input ?? ""); return true; } return false; } } browser.JSDialogHandler = new CustomJSDialogHandler(); ``` -------------------------------- ### CefRuntimeLoader API Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Documentation for initializing and loading the CEF runtime, including methods, properties, and platform-specific behaviors. ```APIDOC ## CefRuntimeLoader ### Description Provides methods for initializing and loading the CEF runtime. ### Methods - **Initialize()**: Initializes the CEF runtime. - **Load()**: Loads the CEF runtime. ### Properties - **IsLoaded** (bool): Indicates if the CEF runtime is loaded. - **IsOSREnabled** (bool): Indicates if Off-Screen Rendering is enabled. ### Error Handling Details on error handling and troubleshooting during runtime initialization. ### Platform Specifics Information on platform-specific behavior for Windows, macOS, and Linux. ``` -------------------------------- ### Initialize CefBrowserSettings Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/configuration.md Configure browser rendering and behavior by initializing CefBrowserSettings. Changes made before browser initialization are respected. ```csharp var browserSettings = new CefBrowserSettings { DefaultFontSize = 14, Javascript = CefState.Enabled, WebSecurity = CefState.Enabled, LocalStorage = CefState.Enabled, Plugins = CefState.Disabled }; var browser = new AvaloniaCefBrowser(); // Note: Settings are accessed via browser.Settings property // Changes before browser initialization are respected ``` -------------------------------- ### Initialize and Load URL in Avalonia Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Demonstrates how to initialize CEF runtime and load a URL in an Avalonia application using AvaloniaCefBrowser. Ensure CefRuntimeLoader.Initialize() is called once. ```csharp using Xilium.CefGlue.Avalonia; using Xilium.CefGlue.Common; public class MainWindow { private AvaloniaCefBrowser _browser; public MainWindow() { // Initialize once if (!CefRuntimeLoader.IsLoaded) CefRuntimeLoader.Initialize(); _browser = new AvaloniaCefBrowser(); _browser.BrowserInitialized += () => _browser.Address = "https://example.com"; } } ``` -------------------------------- ### Initialize CefGlue Runtime Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Initializes the CefGlue runtime with specified settings, command-line flags, and custom schemes. Ensure this is called before any browser instances are created. The `Load` method should be called subsequently to load the handler. ```csharp CefRuntimeLoader.Initialize(settings, flags, schemes); CefRuntimeLoader.Load(handler); ``` -------------------------------- ### Zoom Control Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/WpfCefBrowser.md Control the zoom level of the browser. You can get the current level, set a specific level, or use preset zoom commands like ZoomIn, ZoomOut, and ZoomReset. ```csharp // Get current zoom level double currentZoom = _browser.ZoomLevel; // Set zoom level _browser.ZoomLevel = 0.0; // 100% (default) _browser.ZoomLevel = 1.0; // 200% _browser.ZoomLevel = -1.0; // 50% // Use preset commands _browser.Zoom(CefZoomCommand.ZoomIn); _browser.Zoom(CefZoomCommand.ZoomOut); _browser.Zoom(CefZoomCommand.ZoomReset); ``` -------------------------------- ### CefRuntimeLoader Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Manages the initialization and lifecycle of the CEF runtime. Users should call Initialize() once at application startup. ```APIDOC ## CefRuntimeLoader ### Description Manages the initialization and lifecycle of the CEF runtime. Users should call Initialize() once at application startup. ### Methods - **Initialize()**: Configures and initializes the CEF runtime. - **Load()**: Loads the configured CEF runtime. ### Properties - **IsLoaded** (bool): Checks if the CEF runtime is ready. ``` -------------------------------- ### Verify macOS Resources Before Initialization Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/errors.md On macOS, check for the existence of the Resources directory before calling CefRuntimeLoader.Initialize() to prevent a FileNotFoundException. This ensures necessary CEF resources are available. ```csharp if (CefRuntime.Platform == CefRuntimePlatform.MacOS) { // Verify Resources directory exists before initialization var resourcesPath = System.IO.Path.Combine( AppContext.BaseDirectory, "Resources"); if (!System.IO.Directory.Exists(resourcesPath)) { throw new InvalidOperationException("Resources directory not found"); } } CefRuntimeLoader.Initialize(); ``` -------------------------------- ### CefRuntimeLoader Initialization with Custom Schemes Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Initializes the CEF runtime and registers custom URL schemes. This is useful for handling custom protocols within your application. ```csharp var customSchemes = new[] { new CustomScheme { SchemeName = "app", DomainName = "", IsStandard = true, IsSecure = true, SchemeHandlerFactory = new AppSchemeHandlerFactory() } }; CefRuntimeLoader.Initialize(null, null, customSchemes); ``` -------------------------------- ### Register Javascript Object with MethodCallHandler Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/types.md Example of registering a C# object with a JavaScript object name and a handler for method calls. The handler can be used to intercept and process method invocations from JavaScript. ```csharp public class HostAPI { public void DoSomething(string param) { } } MethodCallHandler handler = (method) => { System.Diagnostics.Debug.WriteLine($"Method called: {method}"); }; var api = new HostAPI(); browser.RegisterJavascriptObject(api, "api", handler); ``` -------------------------------- ### IsBrowserInitialized Property Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Returns true if the underlying CEF browser has been initialized and is ready for use. ```APIDOC ## IsBrowserInitialized Property ### Description Returns `true` if the underlying CEF browser has been initialized and is ready for use. ### Type bool ### Remarks The browser is initialized lazily when first displayed. Use the `BrowserInitialized` event to know when the browser is ready. ``` -------------------------------- ### Handle Downloads Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/WpfCefBrowser.md Handle file downloads by specifying a save path and whether to show a save dialog. The OnBeforeDownload event is triggered when a download is initiated. ```csharp // Handle downloads _browser.DownloadHandler = new DownloadHandler { OnBeforeDownload = (browser, downloadItem, suggestedName, callback) => { string savePath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Downloads), suggestedName); callback.Continue(savePath, showDialog: false); } }; ``` -------------------------------- ### Handle Loading State Change Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/MANIFEST.txt Responds to changes in the browser's loading state, such as when it starts or stops loading content. This event is useful for updating UI elements like progress indicators. ```csharp browser.LoadingStateChange += (sender, args) => { // Handle loading state change }; ``` -------------------------------- ### Execute and Evaluate JavaScript Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/WpfCefBrowser.md Demonstrates executing JavaScript without waiting for a result and evaluating JavaScript to retrieve typed data. Includes a sample class for strongly-typed results. ```csharp // Execute JavaScript without waiting for result _browser.ExecuteJavaScript("console.log('Hello from .NET');"); // Evaluate JavaScript and get result var result = await _browser.EvaluateJavaScript( "({ title: document.title, url: window.location.href })"); // Strongly-typed result var documentInfo = await _browser.EvaluateJavaScript( @"({ title: document.title, url: window.location.href, readyState: document.readyState, characterSet: document.characterSet })"); MessageBox.Show($"Title: {documentInfo.title}\nURL: {documentInfo.url}"); public class DocumentInfo { public string title { get; set; } public string url { get; set; } public string readyState { get; set; } public string characterSet { get; set; } } ``` -------------------------------- ### Create AvaloniaCefBrowser Instance Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Demonstrates how to create a new AvaloniaCefBrowser control. You can optionally provide a factory function to create a custom request context. ```csharp public AvaloniaCefBrowser(Func cefRequestContextFactory = null) ``` ```csharp // Basic browser var browser = new AvaloniaCefBrowser(); ``` ```csharp // Browser with custom request context var browser = new AvaloniaCefBrowser(() => { var settings = new CefRequestContextSettings(); return CefRequestContext.CreateContext(settings); }); ``` -------------------------------- ### Handle Browser Initialization Event Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Subscribe to the BrowserInitialized event to execute code once the browser is ready. This is a common place to set the initial URL. ```csharp browser.BrowserInitialized += () => { browser.Address = "https://example.com"; }; ``` -------------------------------- ### Implement Custom Display Handling Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Override methods in DisplayHandler to customize how browser events like address changes, title updates, status messages, and console messages are handled. This example updates UI elements and logs console messages. ```csharp public class CustomDisplayHandler : DisplayHandler { protected override void OnAddressChange(CefBrowser browser, CefFrame frame, string url) { // Update UI with new address MainWindow.Instance.AddressTextBox.Text = url; } protected override void OnTitleChange(CefBrowser browser, string title) { MainWindow.Instance.Title = title; } protected override void OnStatusMessage(CefBrowser browser, string value) { MainWindow.Instance.StatusLabel.Text = value; } protected override bool OnConsoleMessage( CefBrowser browser, CefLogSeverity level, string message, string source, int line) { System.Diagnostics.Debug.WriteLine($"[{level}] {message} ({source}:{line})"); return false; // Let default handling occur } protected override void OnLoadingProgressChange(CefBrowser browser, double progress) { MainWindow.Instance.ProgressBar.Value = progress * 100; } } browser.DisplayHandler = new CustomDisplayHandler(); ``` -------------------------------- ### Configuration Reference Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/INDEX.md Details runtime and browser settings, including CefSettings, CefBrowserSettings, and command-line flags. ```APIDOC ## Configuration Reference ### Description This section outlines the various settings and configurations available for the CEF runtime and individual browsers, covering a wide range of properties and command-line options. ### Configuration Objects - **CefSettings**: Over 30 properties for configuring the CEF runtime, including cache, user agent, logging, and platform-specific options. - **CefBrowserSettings**: Over 25 properties for configuring individual browser instances, such as font settings, JavaScript enablement, plugin handling, and security options. - **CefRequestContextSettings**: Configuration for request contexts, affecting cookies, cache, and authentication handling. ### Enumerations - **CefState**: Defines states used in various configuration settings. ### Command-Line Flags Documentation for over 20 common command-line flags that can be used to control CEF behavior at startup. ### Environment Variables Information on relevant environment variables that can influence CEF runtime configuration. ### Platform-Specific Notes Includes guidance on configuration specific to different operating systems. ### Examples Provides complete initialization examples demonstrating how to apply these settings. ``` -------------------------------- ### macOS CefRuntimeLoader Initialization Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md On macOS, CefRuntimeLoader must be initialized with AvaloniaBrowserProcessHandler before creating the first AvaloniaCefBrowser. This is automatically handled in the static constructor. ```csharp static AvaloniaCefBrowser() { if (CefRuntime.Platform == CefRuntimePlatform.MacOS && !CefRuntimeLoader.IsLoaded) { CefRuntimeLoader.Load(new AvaloniaBrowserProcessHandler()); } } ``` -------------------------------- ### Custom Download Handler Implementation Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/Handlers.md Implement a custom DownloadHandler to control file download paths and monitor progress. Override OnBeforeDownload to specify the download location and OnDownloadUpdated to track progress. ```csharp public class CustomDownloadHandler : DownloadHandler { protected override void OnBeforeDownload( CefBrowser browser, CefDownloadItem downloadItem, string suggestedName, IDownloadItemCallback callback) { string downloadPath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Downloads), suggestedName); callback.Continue(downloadPath, showDialog: false); } protected override void OnDownloadUpdated( CefBrowser browser, CefDownloadItem downloadItem, IDownloadItemCallback callback) { long totalBytes = downloadItem.TotalBytes; long receivedBytes = downloadItem.ReceivedBytes; int progress = totalBytes > 0 ? (int)(receivedBytes * 100 / totalBytes) : 0; System.Diagnostics.Debug.WriteLine($"Download progress: {progress}%"); } } browser.DownloadHandler = new CustomDownloadHandler(); ``` -------------------------------- ### AvaloniaCefBrowser Code-Behind Initialization and Event Handling Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Initializes the AvaloniaCefBrowser, sets up event handlers for browser events, and performs initial navigation. Ensure CefRuntimeLoader.Initialize() is called if not already done. ```csharp using Avalonia.Controls; using Xilium.CefGlue.Avalonia; using Xilium.CefGlue.Common; public partial class MainWindow : Window { private AvaloniaCefBrowser _browser; public MainWindow() { InitializeComponent(); // Initialize CEF if not already done if (!CefRuntimeLoader.IsLoaded) { CefRuntimeLoader.Initialize(); } _browser = this.FindControl("Browser"); // Set up event handlers _browser.BrowserInitialized += OnBrowserInitialized; _browser.AddressChanged += OnAddressChanged; _browser.LoadStart += OnLoadStart; _browser.LoadEnd += OnLoadEnd; _browser.ConsoleMessage += OnConsoleMessage; // Navigate to initial page _browser.Address = "https://example.com"; } private void OnBrowserInitialized() { // Browser is ready } private void OnAddressChanged(dynamic args) { AddressBox.Text = _browser.Address; } private void OnLoadStart(dynamic args) { StatusLabel.Content = "Loading..."; } private void OnLoadEnd(dynamic args) { StatusLabel.Content = "Done"; } private void OnConsoleMessage(dynamic args) { System.Diagnostics.Debug.WriteLine($"[Console] {args.Message}"); } private void OnGoBack() { if (_browser.CanGoBack) _browser.GoBack(); } private void OnGoForward() { if (_browser.CanGoForward) _browser.GoForward(); } private void OnReload() { _browser.Reload(); } private void OnNavigate() { _browser.Address = AddressBox.Text; } } ``` -------------------------------- ### Configure Browser Settings Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/configuration.md Set default browser settings such as font size, JavaScript, web security, and local storage before navigating to a URL. Changes to these settings after initialization will not take effect. ```csharp var browser = new AvaloniaCefBrowser(); // Configure before navigation (changes after init don't apply) browser.Settings.DefaultFontSize = 14; browser.Settings.Javascript = CefState.Enabled; browser.Settings.WebSecurity = CefState.Enabled; browser.Settings.LocalStorage = CefState.Enabled; // Navigate browser.Address = "https://example.com"; ``` -------------------------------- ### Register .NET API for JavaScript Access Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/README.md Illustrates how to expose .NET methods and properties to JavaScript code running in the browser. Define a .NET class with methods and register it using RegisterJavascriptObject. ```csharp // Define .NET API public class HostAPI { public string GetAppVersion() => "1.0.0"; public void ShowAlert(string message) => MessageBox.Show(message); public async Task FetchDataAsync(int id) => await Api.Get(id); } // Register var api = new HostAPI(); browser.RegisterJavascriptObject(api, "hostAPI"); // From JavaScript: // hostAPI.getAppVersion() // hostAPI.showAlert("Hello") // await hostAPI.fetchDataAsync(42) ``` -------------------------------- ### Initialize CEF Runtime Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/WpfCefBrowser.md Call this static method in your App.xaml.cs during application startup to initialize the CEF runtime. Ensure it's called before creating any windows. Custom settings and flags can be provided. ```csharp public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // Initialize CEF before creating any windows if (!CefRuntimeLoader.IsLoaded) { var settings = new CefSettings { CachePath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp", "Cache") }; var flags = new[] { KeyValuePair.Create("disable-features", "FirstPartySets") }; CefRuntimeLoader.Initialize(settings, flags); } } } ``` -------------------------------- ### Create AvaloniaCefBrowser Instance Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Instantiates an AvaloniaCefBrowser using the default request context. This is a common way to create a browser instance for Avalonia applications. ```csharp var browser = new AvaloniaCefBrowser(); ``` -------------------------------- ### Initialize AvaloniaCefBrowser with Window Rendering Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/AvaloniaCefBrowser.md Instantiates AvaloniaCefBrowser using the default window rendering mode. This mode utilizes native Avalonia controls for optimal performance and standard browser appearance. ```csharp var browser = new AvaloniaCefBrowser(); // Rendering is windowed by default ``` -------------------------------- ### Show Developer Tools Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/BaseCefBrowser.md Opens the browser's Developer Tools window, providing access to the Inspector, Console, and Debugger. ```csharp public void ShowDeveloperTools() ``` ```csharp browser.ShowDeveloperTools(); ``` -------------------------------- ### WpfCefBrowser() Constructor Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/WpfCefBrowser.md Creates a new WPF CEF browser control with default settings. This is the simplest way to instantiate the browser control. ```APIDOC ## WpfCefBrowser() ### Description Creates a new WPF CEF browser control with default settings. ### Method Signature ```csharp public WpfCefBrowser() ``` ### Example ```csharp var browser = new WpfCefBrowser(); ``` ``` -------------------------------- ### Check and Initialize CEF Runtime Source: https://github.com/outsystems/cefglue/blob/main/_autodocs/api-reference/CefRuntimeLoader.md Use this snippet to check if the CEF runtime is loaded and initialize it if necessary. Ensure CefRuntimeLoader.Initialize() is called before creating browsers. ```csharp if (!CefRuntimeLoader.IsLoaded) { CefRuntimeLoader.Initialize(); } ```