webview2

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 13 Imported by: 0

README

Go Go Report Card Go Reference

go-webview2

This package provides an interface for using the Microsoft Edge WebView2 component with Go. It is based on webview/webview and provides a compatible API.

Please note that this package only supports Windows, since it provides functionality specific to WebView2. If you wish to use this library for Windows, but use webview/webview for all other operating systems, you could use the go-webview-selector package instead. However, you will not be able to use WebView2-specific functionality.

If you wish to build desktop applications in Go using web technologies, please consider Wails. It uses go-webview2 internally on Windows.

If you are using Windows 10+, the WebView2 runtime should already be installed. If not, download it from:

WebView2 runtime

Requirements

  • Go 1.21 or later - This library uses runtime.Pinner to ensure safe interaction with native Windows COM code
  • Windows 10+ with WebView2 runtime installed

Basic Usage

package main

import (
    "github.com/Krakinsight/go-webview2"
)

func main() {
    w := webview2.NewWithOptions(webview2.WebViewOptions{
        Debug:     true,
        AutoFocus: true,
        WindowOptions: webview2.WindowOptions{
            Title:  "My App",
            Width:  800,
            Height: 600,
            Center: true,
        },
    })
    
    if w == nil {
        panic("Failed to load webview")
    }
    defer w.Destroy()
    
    w.Navigate("https://example.com")
    w.Run()
}

Features

Window Positioning

The Location struct allows precise window positioning:

// Position from top-left corner
Location: &webview2.Location{X: 100, Y: 100}

// Position from bottom-right corner using negative coordinates
Location: &webview2.Location{X: -500, Y: -1}

Note: Negative coordinates use Windows work area (excludes taskbar), ensuring windows never overlap the taskbar.

Custom User-Agent
webview2.NewWithOptions(webview2.WebViewOptions{
    UserAgent: "MyApp/1.0 (CustomBrowser)",
})
Access to WebView2 Settings
w := webview2.NewWithOptions(...)
settings := w.GetSettings()

// Configure zoom controls
settings.PutIsZoomControlEnabled(false)

// Disable browser accelerator keys
settings.PutAreBrowserAcceleratorKeysEnabled(false)
Accelerator Keys
w.SetAcceleratorKeyCallback(func(virtualKey uint) bool {
    switch virtualKey {
    case 0x74: // VK_F5
        fmt.Println("Blocked F5 refresh")
        return true // Block the key
    case 0x7B: // VK_F12  
        fmt.Println("Blocked DevTools")
        return true
    default:
        return false // Allow other keys
    }
})

Common virtual key codes:

  • 0x74 - F5 (Refresh)
  • 0x7B - F12 (DevTools)
  • 0x41-0x5A - Letters A-Z
  • 0x30-0x39 - Numbers 0-9

See Virtual-Key Codes for complete reference.

Window Styles
  • WindowStyleDefault - Standard resizable window
  • WindowStyleFixed - Non-resizable window
  • WindowStyleBorderless - No borders/title bar (custom UI)
  • WindowStyleToolWindow - Tool window (not in taskbar)
DPI Awareness

Control how your application handles high-DPI displays to ensure crisp rendering across different display configurations:

w := webview2.NewWithOptions(webview2.WebViewOptions{
    WindowOptions: webview2.WindowOptions{
        Title:                "My DPI-Aware App",
        Width:                800,
        Height:               600,
        DpiAwarenessContext:  webview2.DpiAwarenessContextPerMonitorAwareV2,
    },
})
Available DPI Awareness Modes:
  • DpiAwarenessContextDefault - System default (no explicit setting)
  • DpiAwarenessContextUnaware - Windows handles scaling (may appear blurry)
  • DpiAwarenessContextSystemAware - Scales to primary monitor DPI
  • DpiAwarenessContextPerMonitorAware - Adapts to each monitor
  • DpiAwarenessContextPerMonitorAwareV2 - Recommended for Windows 10 1703+
  • DpiAwarenessContextUnawareGdiScaled - Improved unaware mode (Windows 10 1809+)

Recommendation: Use DpiAwarenessContextPerMonitorAwareV2 for modern applications to ensure crisp rendering across all displays. This setting is particularly important for applications that will be used on high-DPI monitors or multi-monitor setups with different DPI settings.

Note: The DPI awareness setting affects the entire process and should be set early during window creation. On older Windows versions where the API is unavailable, the setting is silently ignored for backward compatibility.

WebAuthn Bridge

WebView2's sandbox blocks direct access to the platform authenticator (Windows Hello / FIDO2). The WebAuthn bridge intercepts navigator.credentials API calls and routes them through native Go handlers.

Operation flow:

  1. OnUserApproval (optional gate) — return true to abort, false/nil to continue
  2. Windows Hello via webauthn.dll (full CTAP2 support, including plugin authenticators)
  3. If Windows Hello fails and OnWindowsHelloFallback returns true → internal ECDSA P-256 fallback with encrypted file storage

Setup via WebViewOptions (recommended):

w := webview2.NewWithOptions(webview2.WebViewOptions{
    WindowOptions: webview2.WindowOptions{
        Title:  "My App",
        Width:  800,
        Height: 600,
        Center: true,
    },
    WebAuthn: webview2.WebAuthnOptions{
        // Enabled activates the bridge automatically
        Enabled: true,

        // Optional: fully replace the create flow (bypasses Windows Hello + ECDSA fallback).
        // Useful to delegate credential creation to an external server or HSM.
        // When set, OnUserApproval, OnWindowsHelloFallback and Store are ignored for create.
        CreateHandler: func(opts webview2.WebAuthnCreateOptions) (webview2.WebAuthnCredential, error) {
            // call your server / HSM here
            return myServer.Register(opts)
        },

        // Optional: fully replace the get flow (bypasses Windows Hello + ECDSA fallback).
        // When set, OnUserApproval, OnWindowsHelloFallback and Store are ignored for get.
        GetHandler: func(opts webview2.WebAuthnGetOptions) (webview2.WebAuthnAssertion, error) {
            return myServer.Authenticate(opts)
        },

        // Optional: gate called before any Windows Hello operation.
        // Return true to abort, false to proceed.
        // Only used when CreateHandler/GetHandler are nil.
        OnUserApproval: func(op webview2.WebAuthnOperation) bool {
            log.Printf("WebAuthn %s for RP=%s user=%s", op.Type, op.RPID, op.User.Name)
            return false // always allow
        },

        // Optional: called when Windows Hello fails.
        // Return true to use internal ECDSA fallback, false to propagate the error.
        // Only used when CreateHandler/GetHandler are nil.
        OnWindowsHelloFallback: func(op webview2.WebAuthnOperation, err error) bool {
            log.Printf("Windows Hello failed (%v), using ECDSA fallback", err)
            return true
        },

        // Optional: custom credential store.
        // nil = default AES-GCM encrypted file in %APPDATA%\go-webview2\
        Store: nil,

        // Optional: operation timeout in seconds (0 = default 60s)
        Timeout: 120,
    },
})

Manual setup (advanced):

w := webview2.NewWithOptions(...)
bridge := w.EnableWebAuthnBridge()
bridge.OnUserApproval = func(op webview2.WebAuthnOperation) bool { return false }
bridge.OnWindowsHelloFallback = func(op webview2.WebAuthnOperation, err error) bool { return true }
bridge.Store = webview2.NewInMemoryCredentialStore() // or your own implementation
bridge.SetTimeout(90 * time.Second)

Error handling:

All errors are typed and can be matched with errors.Is:

import "errors"

// Check specific error conditions
if errors.Is(err, webview2.ErrWindowsHelloNoCredential) {
    // No Windows Hello credential for this RP
}
if errors.Is(err, webview2.ErrOperationCancelledByUser) {
    // User denied the operation
}

Credential Storage:

The bridge supports pluggable credential storage via the CredentialStore interface:

type CredentialStore interface {
    Save(credential StoredCredential) error
    Load(credentialID string) (StoredCredential, error)
    LoadAll(rpID string) ([]StoredCredential, error)
    Delete(credentialID string) error
}

Available implementations:

  • NewInMemoryCredentialStore() — for testing (no persistence, no encryption)
  • Default file store (used when Store: nil) — AES-GCM encrypted, key derived from Windows user SID, stored in %APPDATA%\go-webview2\webauthn_credentials.enc
  • Custom implementation — inject via bridge.Store or WebAuthnOptions.Store

Windows Hello / CTAP plugins:

if webview2.IsWebAuthnDLLAvailable() {
    version, _ := webview2.GetWebAuthnAPIVersion()
    log.Printf("Windows Hello available (API version: %d)", version)
}

Windows Hello plugin authenticators (1Password, Bitwarden, etc.) are automatically supported — webauthn.dll orchestrates authenticator selection internally. No extra configuration needed.

Supported algorithms: ES256, ES384, ES512, RS256, RS384, RS512, PS256, PS384, PS512.

JavaScript API — unchanged:

The bridge transparently intercepts the standard WebAuthn JavaScript API:

// Register a new credential
const credential = await navigator.credentials.create({
    publicKey: {
        challenge: new Uint8Array(32),
        rp: { name: "My App", id: window.location.hostname },
        user: {
            id: new Uint8Array(16),
            name: "user@example.com",
            displayName: "User"
        },
        pubKeyCredParams: [
            { type: "public-key", alg: -7 },   // ES256
            { type: "public-key", alg: -257 }   // RS256
        ],
        authenticatorSelection: { userVerification: "required" }
    }
});

// Authenticate with a credential
const assertion = await navigator.credentials.get({
    publicKey: {
        challenge: new Uint8Array(32),
        rpId: window.location.hostname,   // ← always set rpId explicitly
        allowCredentials: [{
            type: "public-key",
            id: credentialIdBytes         // Uint8Array of raw credential ID bytes
        }],
        userVerification: "required"
    }
});

Important: always pass rpId explicitly in navigator.credentials.get(). If omitted, the bridge defaults to window.location.hostname but Windows Hello may reject it if it differs from the enrolled origin.

Key Features:

  • Bypasses WebView2 sandbox limitations
  • Full Windows Hello / CTAP2 integration including plugin authenticators
  • Internal ECDSA P-256 fallback for environments without Windows Hello
  • Thread-safe (one operation at a time)
  • Configurable timeouts
  • Pluggable credential storage
  • All errors typed and matchable with errors.Is
Window Close from JavaScript

You cannot create a binding named close() because it conflicts with the built-in window.close() function. However, you can easily add a closewebview() function in JavaScript by binding it to w.Destroy():

w := webview2.NewWithOptions(webview2.WebViewOptions{
    Debug:     true,
    WindowOptions: webview2.WindowOptions{
        Title:  "My App",
        Width:  800,
        Height: 600,
    },
})

// Bind close function
w.Bind("closewebview", func() {
    w.Destroy()
})

Then in JavaScript:

// Simple close button
<button onclick="closewebview()">Close Window</button>

// With confirmation
<button onclick="if(confirm('Close?')) closewebview()">Close</button>

Demos

Available Demos

Basic centered window:

go run ./cmd/demo-basic

Positioned window with custom style:

go run ./cmd/demo-positioned

Borderless window:

go run ./cmd/demo-borderless

Tool window (top-right):

go run ./cmd/demo-toolwindow

Bottom-right positioned:

go run ./cmd/demo-bottomright

DPI awareness demonstration:

go run ./cmd/demo-dpi-aware

Accelerator keys (F5/F12 blocking):

go run ./cmd/demo-accelerator-keys

Window close from JavaScript:

go run ./cmd/demo-close

WebAuthn bridge demonstration:

go run ./cmd/demo-webauthn

This will use go-winloader to load an embedded copy of WebView2Loader.dll. If you want, you can also provide a newer version of WebView2Loader.dll in the DLL search path and it should be picked up instead. It can be acquired from the WebView2 SDK (which is permissively licensed.)

Documentation

Index

Constants

View Source
const (
	WEBAUTHN_API_VERSION_1                               = 1
	WEBAUTHN_API_VERSION_2                               = 2
	WEBAUTHN_API_VERSION_3                               = 3
	WEBAUTHN_API_VERSION_4                               = 4
	WEBAUTHN_API_CURRENT_VERSION                         = WEBAUTHN_API_VERSION_4
	WEBAUTHN_HASH_ALGORITHM_SHA_256                      = "SHA-256"
	WEBAUTHN_HASH_ALGORITHM_SHA_384                      = "SHA-384"
	WEBAUTHN_HASH_ALGORITHM_SHA_512                      = "SHA-512"
	WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY                  = "public-key"
	WEBAUTHN_USER_VERIFICATION_REQUIREMENT_ANY           = 0
	WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED      = 1
	WEBAUTHN_USER_VERIFICATION_REQUIREMENT_PREFERRED     = 2
	WEBAUTHN_USER_VERIFICATION_REQUIREMENT_DISCOURAGED   = 3
	WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_ANY       = 0
	WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_NONE      = 1
	WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_INDIRECT  = 2
	WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_DIRECT    = 3
	WEBAUTHN_AUTHENTICATOR_ATTACHMENT_ANY                = 0
	WEBAUTHN_AUTHENTICATOR_ATTACHMENT_PLATFORM           = 1
	WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM     = 2
	WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM_U2F = 3

	// COSE algorithm identifiers
	WEBAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256        = -7
	WEBAUTHN_COSE_ALGORITHM_ECDSA_P384_WITH_SHA384        = -35
	WEBAUTHN_COSE_ALGORITHM_ECDSA_P521_WITH_SHA512        = -36
	WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA256 = -257
	WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA384 = -258
	WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA512 = -259
	WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA256           = -37
	WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA384           = -38
	WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA512           = -39

	// HRESULT codes returned by webauthn.dll
	// NTE_NO_KEY: no Windows Hello credential exists for this RP/user
	WEBAUTHN_NTE_NO_KEY = uintptr(0x8009000d)
)

Constants from webauthn.h

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceleratorKeyCallback added in v0.1.0

type AcceleratorKeyCallback func(virtualKey uint) bool

************************************************************************************************ AcceleratorKeyCallback is called when a keyboard accelerator key is pressed. It receives the virtual key code and returns true if the event was handled.

Virtual key codes are defined by Windows: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

Common examples:

  • VK_F5 (0x74) for F5
  • VK_F12 (0x7B) for F12
  • 'A' (0x41) for the A key

The callback is invoked on KEY_DOWN events only (not on KEY_UP or repeat). Return true to mark the key as handled and prevent default browser behavior. Return false to allow the browser to handle the key normally.

Example usage:

w.SetAcceleratorKeyCallback(func(virtualKey uint) bool {
    if virtualKey == 0x74 { // VK_F5
        fmt.Println("F5 pressed - refresh blocked")
        return true // Block default refresh
    }
    if virtualKey == 0x7B { // VK_F12
        fmt.Println("F12 pressed - DevTools blocked")
        return true // Block DevTools
    }
    return false // Allow other keys
})

type AssertionResponse added in v0.1.1

type AssertionResponse struct {
	ClientDataJSON    string `json:"clientDataJSON"`
	AuthenticatorData string `json:"authenticatorData"`
	Signature         string `json:"signature"`
	UserHandle        string `json:"userHandle,omitempty"`
}

AssertionResponse contains the assertion response data

type AuthenticatorSelection added in v0.1.1

type AuthenticatorSelection struct {
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
	RequireResidentKey      bool   `json:"requireResidentKey,omitempty"`
	UserVerification        string `json:"userVerification,omitempty"`
}

AuthenticatorSelection represents authenticator selection criteria

type CredentialResponse added in v0.1.1

type CredentialResponse struct {
	ClientDataJSON    string `json:"clientDataJSON"`
	AttestationObject string `json:"attestationObject"`
}

CredentialResponse contains the credential response data

type DpiAwarenessContext

type DpiAwarenessContext int

************************************************************************************************ DpiAwarenessContext defines how the application handles DPI scaling on Windows. Different modes determine how Windows scales the application's windows and content on high-DPI displays. Setting DPI awareness ensures crisp rendering across different display configurations.

References:

const (
	// DpiAwarenessContextDefault uses the system default DPI awareness.
	// This is the default behavior if no DPI awareness is explicitly set.
	// When set to 0 (default value), no DPI awareness configuration is applied.
	DpiAwarenessContextDefault DpiAwarenessContext = 0

	// DpiAwarenessContextUnaware means the application is DPI unaware.
	// Windows will bitmap stretch the window on high-DPI displays, which may appear blurry.
	// Value: -1 (DPI_AWARENESS_CONTEXT_UNAWARE)
	DpiAwarenessContextUnaware DpiAwarenessContext = -1

	// DpiAwarenessContextSystemAware means the application is system DPI aware.
	// It scales to match the DPI of the primary display at application startup.
	// Does not adapt when moved to monitors with different DPI settings.
	// Value: -2 (DPI_AWARENESS_CONTEXT_SYSTEM_AWARE)
	DpiAwarenessContextSystemAware DpiAwarenessContext = -2

	// DpiAwarenessContextPerMonitorAware means the application is per-monitor DPI aware.
	// It checks the DPI when created and adjusts scale factors when DPI changes.
	// Requires Windows 10 Anniversary Update (1607) or later.
	// Value: -3 (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE)
	DpiAwarenessContextPerMonitorAware DpiAwarenessContext = -3

	// DpiAwarenessContextPerMonitorAwareV2 provides enhanced per-monitor DPI awareness.
	// Similar to V1 but with improved support for mixed-mode DPI scaling and child window DPI scaling.
	// Recommended for modern Windows 10+ applications.
	// Requires Windows 10 Creators Update (1703) or later.
	// Value: -4 (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
	DpiAwarenessContextPerMonitorAwareV2 DpiAwarenessContext = -4

	// DpiAwarenessContextUnawareGdiScaled is DPI unaware with improved GDI scaling.
	// Better than basic unaware mode with less blurry text rendering.
	// Requires Windows 10 October 2018 Update (1809) or later.
	// Value: -5 (DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED)
	DpiAwarenessContextUnawareGdiScaled DpiAwarenessContext = -5
)

type Hint

type Hint int

Hint is used to configure window sizing and resizing behavior.

const (
	// HintNone specifies that width and height are default size
	HintNone Hint = iota

	// HintFixed specifies that window size can not be changed by a user
	HintFixed

	// HintMin specifies that width and height are minimum bounds
	HintMin

	// HintMax specifies that width and height are maximum bounds
	HintMax
)

type PubKeyCredParam added in v0.1.1

type PubKeyCredParam struct {
	Type string `json:"type"`
	Alg  int    `json:"alg"`
}

PubKeyCredParam represents a public key credential parameter

type RelyingParty added in v0.1.1

type RelyingParty struct {
	Name string `json:"name"`
	ID   string `json:"id,omitempty"`
}

RelyingParty represents the relying party information

type User added in v0.1.1

type User struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
}

User represents the user information

type WebAuthnAssertion added in v0.1.1

type WebAuthnAssertion struct {
	ID       string            `json:"id"`
	RawID    string            `json:"rawId"`
	Type     string            `json:"type"`
	Response AssertionResponse `json:"response"`
}

WebAuthnAssertion represents an assertion result

type WebAuthnBridge added in v0.1.1

type WebAuthnBridge struct {
	// CreateHandler fully replaces the default create flow (Windows Hello + ECDSA fallback).
	// When set, OnUserApproval, OnWindowsHelloFallback and Store are ignored for create operations.
	// Useful to delegate credential creation to an external server, HSM, or custom authenticator.
	CreateHandler func(options WebAuthnCreateOptions) (WebAuthnCredential, error)

	// GetHandler fully replaces the default get flow (Windows Hello + ECDSA fallback).
	// When set, OnUserApproval, OnWindowsHelloFallback and Store are ignored for get operations.
	// Useful to delegate assertion to an external server, HSM, or custom authenticator.
	GetHandler func(options WebAuthnGetOptions) (WebAuthnAssertion, error)

	// OnUserApproval is an optional pre-check gate called before Windows Hello.
	// Ignored when CreateHandler/GetHandler are set.
	// - nil: proceed directly to Windows Hello (no gate)
	// - returns false: proceed to Windows Hello (user approved or no preference)
	// - returns true: abort the operation (user explicitly denied/cancelled)
	OnUserApproval func(op WebAuthnOperation) bool

	// OnWindowsHelloFallback is called when Windows Hello fails.
	// Ignored when CreateHandler/GetHandler are set.
	// - nil: return the Windows Hello error to the caller
	// - non-nil: use internal ECDSA implementation as fallback
	// Return true to use internal ECDSA, false to propagate the Windows Hello error.
	OnWindowsHelloFallback func(op WebAuthnOperation, whErr error) bool

	// Store is the credential storage implementation used by the internal ECDSA fallback.
	// If nil, a default encrypted file-based store will be created automatically.
	// You can inject your own implementation by setting this field before calling
	// EnableWebAuthnBridge or by setting it directly on the returned bridge.
	Store CredentialStore
	// contains filtered or unexported fields
}

WebAuthnBridge provides a JavaScript bridge for WebAuthn functionality. Since WebView2's sandbox blocks access to the platform authenticator (Windows Hello/FIDO2), this bridge intercepts navigator.credentials calls and routes them through Go handlers.

Operation flow (when CreateHandler/GetHandler are nil):

  1. OnUserApproval (optional gate): nil or returns false → proceed to Windows Hello. Returns true → abort the operation (user explicitly denied).
  2. Windows Hello via webauthn.dll.
  3. If Windows Hello fails and OnWindowsHelloFallback != nil → use internal ECDSA implementation.

When CreateHandler or GetHandler are set, they fully replace the above flow.

type WebAuthnCreateOptions added in v0.1.1

type WebAuthnCreateOptions struct {
	Challenge              string                 `json:"challenge"`
	RP                     RelyingParty           `json:"rp"`
	User                   User                   `json:"user"`
	PubKeyCredParams       []PubKeyCredParam      `json:"pubKeyCredParams"`
	AuthenticatorSelection AuthenticatorSelection `json:"authenticatorSelection,omitempty"`
	ExcludeCredentials     []string               `json:"excludeCredentials,omitempty"`
	Timeout                int                    `json:"timeout,omitempty"`
	Attestation            string                 `json:"attestation,omitempty"`
	Origin                 string                 `json:"origin,omitempty"` // Page origin for clientDataJSON
}

WebAuthnCreateOptions represents the options for creating a new credential

type WebAuthnCredential added in v0.1.1

type WebAuthnCredential struct {
	ID       string             `json:"id"`
	RawID    string             `json:"rawId"`
	Type     string             `json:"type"`
	Response CredentialResponse `json:"response"`
}

WebAuthnCredential represents a created credential

type WebAuthnGetOptions added in v0.1.1

type WebAuthnGetOptions struct {
	Challenge        string   `json:"challenge"`
	RPID             string   `json:"rpId,omitempty"`
	AllowCredentials []string `json:"allowCredentials,omitempty"`
	Timeout          int      `json:"timeout,omitempty"`
	UserVerification string   `json:"userVerification,omitempty"`
	Origin           string   `json:"origin,omitempty"` // Page origin for clientDataJSON
}

WebAuthnGetOptions represents the options for getting an assertion

type WebAuthnOperation added in v0.1.1

type WebAuthnOperation struct {
	Type   string       // "create" or "get"
	RPID   string       // Relying Party ID
	RPName string       // Relying Party Name
	User   WebAuthnUser // Empty for "get" operations
}

WebAuthnOperation describes what is being requested, passed to the approval callback

type WebAuthnUser added in v0.1.1

type WebAuthnUser struct {
	ID          string // User ID (base64url encoded)
	Name        string // User name (email)
	DisplayName string // Display name
}

WebAuthnUser represents user information for WebAuthn operations

type WebView

type WebView interface {

	// Run runs the main loop until it's terminated. After this function exits -
	// you must destroy the webview.
	Run()

	// Terminate stops the main loop. It is safe to call this function from
	// a background thread.
	Terminate()

	// Dispatch posts a function to be executed on the main thread. You normally
	// do not need to call this function, unless you want to tweak the native
	// window.
	Dispatch(f func())

	// Destroy destroys a webview and closes the native window.
	Destroy()

	// Window returns a native window handle pointer. When using GTK backend the
	// pointer is GtkWindow pointer, when using Cocoa backend the pointer is
	// NSWindow pointer, when using Win32 backend the pointer is HWND pointer.
	Window() unsafe.Pointer

	// SetTitle updates the title of the native window. Must be called from the UI
	// thread.
	SetTitle(title string)

	// SetSize updates native window size. See Hint constants.
	SetSize(w int, h int, hint Hint)

	// Navigate navigates webview to the given URL. URL may be a data URI, i.e.
	// "data:text/text,<html>...</html>". It is often ok not to url-encode it
	// properly, webview will re-encode it for you.
	Navigate(url string)

	// SetHtml sets the webview HTML directly.
	// The origin of the page is `about:blank`.
	SetHtml(html string)

	// Init injects JavaScript code at the initialization of the new page. Every
	// time the webview will open a the new page - this initialization code will
	// be executed. It is guaranteed that code is executed before window.onload.
	Init(js string)

	// Eval evaluates arbitrary JavaScript code. Evaluation happens asynchronously,
	// also the result of the expression is ignored. Use RPC bindings if you want
	// to receive notifications about the results of the evaluation.
	Eval(js string)

	// Bind binds a callback function so that it will appear under the given name
	// as a global JavaScript function. Internally it uses webview_init().
	// Callback receives a request string and a user-provided argument pointer.
	// Request string is a JSON array of all the arguments passed to the
	// JavaScript function.
	//
	// f must be a function
	// f must return either value and error or just error
	Bind(name string, f interface{}) error

	// GetSettings returns the ICoreWebViewSettings interface for configuring WebView2 settings.
	// This provides direct access to all WebView2 configuration options including:
	// - User-Agent customization
	// - Script execution control
	// - Context menu behavior
	// - DevTools availability
	// - Zoom controls
	// - And more...
	GetSettings() *edge.ICoreWebViewSettings

	// SetAcceleratorKeyCallback sets a callback for handling keyboard accelerator keys.
	// The callback receives the virtual key code and returns true if handled.
	//
	// This allows intercepting and handling keyboard shortcuts before the browser
	// processes them. Common use cases include:
	// - Blocking F5 (refresh)
	// - Blocking F12 (DevTools)
	// - Implementing custom keyboard shortcuts
	// - Overriding default browser keyboard behavior
	//
	// The callback is invoked only on KEY_DOWN events (not KEY_UP or repeat).
	// Virtual key codes follow Windows VK_* constants:
	// https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
	//
	// Example:
	//   w.SetAcceleratorKeyCallback(func(vk uint) bool {
	//       if vk == 0x74 { return true } // Block F5
	//       return false
	//   })
	SetAcceleratorKeyCallback(callback AcceleratorKeyCallback)

	// EnableWebAuthnBridge enables the WebAuthn bridge for handling Web Authentication API calls.
	// Since WebView2's sandbox blocks access to the platform authenticator (Windows Hello/FIDO2),
	// this bridge intercepts navigator.credentials calls and routes them through Go handlers.
	//
	// Returns a *WebAuthnBridge that can be used to set custom handlers for credential
	// creation and assertion operations.
	//
	// Example:
	//   bridge := w.EnableWebAuthnBridge()
	//   bridge.SetCreateHandler(func(opts WebAuthnCreateOptions) (WebAuthnCredential, error) {
	//       // Handle credential creation
	//       return credential, nil
	//   })
	EnableWebAuthnBridge() *WebAuthnBridge
}

WebView is the interface for the webview.

type WindowOptions

type WindowOptions struct {
	Title  string
	Width  uint
	Height uint
	IconId uint

	// Location specifies the top-left position of the window.
	// If nil, uses Center behavior if Center is true, otherwise uses OS default.
	// Use the Location struct: &Location{X: 100, Y: 100}
	Location *Location

	// Center centers the window on the screen.
	// Ignored if Location is specified.
	Center bool

	// Style specifies the window style using Windows style constants.
	// Use WindowStyleDefault if not specified (0 value).
	Style WindowStyle

	// DpiAwarenessContext sets the DPI awareness for the process.
	// Use DpiAwarenessContextDefault (0) to skip setting DPI awareness.
	// Recommended: DpiAwarenessContextPerMonitorAwareV2 for modern Windows 10+ apps.
	//
	// Example:
	//   DpiAwarenessContext: webview2.DpiAwarenessContextPerMonitorAwareV2
	//
	// Note: This setting affects the entire process and should be set early.
	// On older Windows versions where the API is unavailable, this setting is silently ignored.
	DpiAwarenessContext DpiAwarenessContext
}

type WindowStyle

type WindowStyle uint32

WindowStyle defines the visual style and behavior of a window.

const (
	// WindowStyleDefault creates a standard overlapped window with title bar,
	// system menu, and thick frame (resizable).
	WindowStyleDefault WindowStyle = 0xCF0000 // WS_OVERLAPPEDWINDOW

	// WindowStyleBorderless creates a window without any borders or decorations.
	// Useful for custom-styled windows or splash screens.
	WindowStyleBorderless WindowStyle = 0x80000000 // WS_POPUP

	// WindowStyleToolWindow creates a tool window with a smaller title bar.
	// Not shown in taskbar.
	WindowStyleToolWindow WindowStyle = 0x00C80080 // WS_EX_TOOLWINDOW | WS_CAPTION

	// WindowStyleFixed creates a non-resizable window with title bar and system menu.
	WindowStyleFixed WindowStyle = 0x00C80000 // WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU

	// WindowStyleDialog creates a dialog-style window.
	WindowStyleDialog WindowStyle = 0x80C80000 // WS_POPUP | WS_CAPTION | WS_SYSMENU
)

Directories

Path Synopsis
cmd
demo-basic command
demo-borderless command
demo-close command
demo-dpi-aware command
demo-positioned command
demo-toolwindow command
demo-webauthn_1 command
demo-webauthn_2 command
internal
w32
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL