webview_go Documentation

repository·master·Indexed 19 days ago

https://github.com/webview/webview_go

A Go language binding for the webview library that enables the creation of desktop applications using HTML, JS, and CSS via a native webview component. The library provides APIs for managing the webview lifecycle, navigating URLs, injecting JavaScript, and binding Go functions to JavaScript.

Tokens
1.6K
Snippets
7
Records
9
Agent score
16%

What's inside webview_go

  1. Timing of Eval() and Dispatch() calls

    master

    When using the webview_go API, ensure that you do not call Eval() or Dispatch() before calling Run().

    Calling these methods before Run() will not work because the webview instance has only been configured at that stage and has not yet been started. The webview lifecycle requires Run() to be invoked to initialize the underlying engine before these interaction methods become functional.

  2. Getting Started with webview_go

    master

    To start a new project using webview_go, follow these steps to initialize your environment and run a basic example:

    1. Initialize your project directory:

      mkdir my-project && cd my-project
    2. Initialize a Go module:

      go mod init example.com/app
    3. Download a basic example: You can fetch the basic example main.go directly from the repository:

      curl -sSLo main.go "https://raw.githubusercontent.com/webview/webview_go/master/examples/basic/main.go"
    4. Install the webview_go dependency:

      go get github.com/webview/webview_go
    5. Build your application: On Windows, use the -ldflags="-H windowsgui" flag to prevent a console window from appearing alongside the webview.

      go build
      # On Windows:
      go build -ldflags="-H windowsgui"
    mkdir my-project && cd my-project
    go mod init example.com/app
    curl -sSLo main.go "https://raw.githubusercontent.com/webview/webview_go/master/examples/basic/main.go"
    go get github.com/webview/webview_go
    go build
  3. Run and manage the webview lifecycle

    master

    The webview lifecycle is managed through the following methods:

    • Run(): Starts the main event loop. This blocks until the loop is terminated. You must call Destroy() after Run() exits to clean up resources.
    • Terminate(): Stops the main event loop. This is safe to call from a background thread.
    • Destroy(): Destroys the webview instance and closes the native window.
    wv := webview.New(false)
    // ... setup ...
    wv.Run()
    wv.Destroy()
  4. Execute JavaScript and Bind Go functions

    master

    To interact between Go and JavaScript:

    • Eval(js string): Evaluates arbitrary JavaScript code asynchronously. The result of the expression is ignored. For receiving data back from JS, use Bind instead.
    • Bind(name string, f interface{}) error: Binds a Go function to a global JavaScript function named name.
      • The function f must be a function.
      • f can return either (value, error) or just error.
      • Arguments passed from JavaScript are provided as a JSON array and automatically unmarshaled into the Go function's arguments.
    • Unbind(name string): Removes a previously bound callback.
    // Bind a Go function to JS
    err := wv.Bind("add", func(a, b int) int {
        return a + b
    })
    if err != nil {
        panic(err)
    }
    
    // In JavaScript, you can now call:
    // const sum = add(5, 10);
    
    // Evaluate JS
    wv.Eval("console.log('Hello from JS')")
  5. Get the native window handle

    master

    The Window() unsafe.Pointer method returns a pointer to the native window handle. The type of the pointer depends on the platform:

    • Linux (GTK): GtkWindow pointer
    • macOS (Cocoa): NSWindow pointer
    • Windows (Win32): HWND pointer
  6. Run code on the main UI thread with Dispatch

    master

    Most native window operations (like SetTitle or SetSize) must be performed on the main UI thread. If you are in a background goroutine, use Dispatch(f func()) to schedule a function to be executed on the main thread.

    go func() {
        // Some background work...
        
        wv.Dispatch(func() {
            // This runs on the UI thread
            wv.SetTitle("Updated Title")
        })
    }()
  7. Initialize a webview instance

    master

    You can create a new webview instance using New or NewWindow.

    • New(debug bool): Creates a new window. If debug is true, developer tools will be enabled (platform permitting).
    • NewWindow(debug bool, window unsafe.Pointer): Creates a webview instance. If the window parameter is a non-null pointer to a native window handle (e.g., GtkWindow on Linux, NSWindow on macOS, or HWND on Windows), the webview will be embedded as a child of that window.
    import "github.com/webview/webview_go"
    
    // Simple new window with debug tools enabled
    wv := webview.New(true)
    defer wv.Destroy()
    
    // Or embed in an existing native window
    // wv := webview.NewWindow(true, nativeWindowHandle)
  8. Configure window size and title

    master

    Use these methods to modify the native window properties:

    • SetTitle(title string): Updates the window title. Must be called from the UI thread (use Dispatch if calling from a goroutine).
    • SetSize(w int, h int, hint Hint): Updates the window size.

    Available Hint constants:

    • HintNone: Default size.
    • HintFixed: The user cannot resize the window.
    • HintMin: Sets minimum width and height bounds.
    • HintMax: Sets maximum width and height bounds.
    import "github.com/webview/webview_go"
    
    // Set title (ensure UI thread)
    wv.SetTitle("My App")
    
    // Set fixed size
    wv.SetSize(800, 600, webview.HintFixed)
  9. Navigate and load content

    master

    Use these methods to control what the webview displays:

    • Navigate(url string): Navigates to a URL. This can be a standard URI (e.g., https://google.com) or a data URI (e.g., data:text/html;base64,...).
    • SetHtml(html string): Sets the webview content directly using an HTML string.
    • Init(js string): Injects JavaScript code that runs at the initialization of every new page. This code is guaranteed to execute before window.onload.
    // Navigate to a URL
    wv.Navigate("https://github.com/webview/webview")
    
    // Load raw HTML
    wv.SetHtml("<h1>Hello World</h1>")
    
    // Inject JS before page load
    wv.Init("console.log('WebView initialized')")