webview2

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 2 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.

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

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

This section is empty.

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 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 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)
}

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
internal
w32
pkg

Jump to

Keyboard shortcuts

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