webview

package module
v0.0.0-...-efe27c6 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2023 License: MIT Imports: 13 Imported by: 0

README

Golang Webview GUI

A tiny cross-platform webview library for Go to build modern cross-platform GUIs.

The goal of the project is to create a common HTML5 UI abstraction layer for the most widely used platforms.

It supports two-way JavaScript bindings (to call JavaScript from Go and to call Go from JavaScript).

Platform Support

Platform Technologies
Linux GTK 3, WebKitGTK
macOS Cocoa, WebKit
Windows Windows API, WebView2

Documentation

See DOC.md

Examples

See Examples

Prerequisites

Your compiler must support minimum C++11 except for platforms that require a more modern version.

Linux and BSD

The GTK and WebKit2GTK libraries are required for development and distribution. You need to check your package repositories regarding how to install those those.

Debian-based systems:

  • Packages:
    • Development: apt install libgtk-3-dev libwebkit2gtk-4.0-dev
    • Production: apt install libgtk-3-0 libwebkit2gtk-4.0-37

Fedora-based systems:

  • Packages:
    • Development: dnf install gtk3-devel webkit2gtk4.0-devel
    • Production: dnf install gtk3 webkit2gtk4.0

BSD-based systems:

  • FreeBSD packages: pkg install webkit2-gtk3
  • Execution on BSD-based systems may require adding the wxallowed option (see mount(8)) to your fstab to bypass W^X memory protection for your executable. Please see if it works without disabling this security feature first.
Windows

Your compiler must support C++17 and we recommend to pair it with an up-to-date Windows 10 SDK.

For Visual C++ we recommend Visual Studio 2022 or later. We have a separate section for MinGW-w64.

Developers and end-users must have the WebView2 runtime installed on their system for any version of Windows before Windows 11.

Getting Started

If you are a developer of this project then please go to the development section.

Instructions here are written for GCC when compiling C/C++ code using Unix-style command lines, and assumes that multiple commands are executed in the same shell session. Command lines for Windows use syntax specific to the Command shell but you can use any shell such as PowerShell as long as you adapt the commands accordingly. See the MinGW-w64 requirements when building on Windows.

You will have a working app but you are encouraged to explore the [available examples][examples] and try the ones that go beyond the mere basics.

Start with creating a new directory structure for your project:

mkdir my-project && cd my-project
mkdir build libs "libs/webview"
Windows Preparation

The WebView2 SDK is required when compiling programs:

mkdir libs\webview2
curl -sSL "https://www.nuget.org/api/v2/package/Microsoft.Web.WebView2" | tar -xf - -C libs\webview2

If you wish to use the official WebView2 loader (WebView2Loader.dll) then grab a copy of the DLL (replace x64 with your target architecture):

copy /Y libs\webview2\build\native\x64\WebView2Loader.dll build

Note: See the WebView2 loader section for more options.

Getting Started with Go

See [Go package documentation][go-docs] for the Go API documentation, or simply read the source code.

Create a new Go module:

go mod init example.com/m

On Windows you will need to make the WebView2 headers discoverable by cgo (see Windows Preperation):

set CGO_CXXFLAGS="-I%cd%\libs\webview2\build\native\include"

Note: Argument quoting works for Go 1.18 and later. Quotes can be removed if paths have no spaces.

Save the basic Go example into your project directory:

curl -sSLo basic.go "https://raw.githubusercontent.com/lexesv/go-webview-gui/main/examples/basic.go"

Install dependencies:

go get github.com/webview/webview

Build and run the example:

# Linux, macOS
go build -o build/basic basic.go && ./build/basic
# Windows
go build -ldflags="-H windowsgui" -o build/basic.exe basic.go && "build/basic.exe"
More Examples

The examples shown here are mere pieces of a bigger picture so we encourage you to try [other examples][examples] and explore on your own—you can follow the same procedure. Please [get in touch][issues-new] if you find any issues.

App Distribution

Distribution of your app is outside the scope of this library but we can give some pointers for you to explore.

macOS Application Bundle

On macOS you would typically create a bundle for your app with an icon and proper metadata.

A minimalistic bundle typically has the following directory structure:

example.app                 bundle
└── Contents
    ├── Info.plist          information property list
    ├── MacOS
    |   └── example         executable
    └── Resources
        └── example.icns    icon

Read more about the structure of bundles at the Apple Developer site.

Tip: The png2icns tool can create icns files from PNG files. See the icnsutils package for Debian-based systems.

Windows Apps

You would typically create a resource script file (*.rc) with information about the app as well as an icon. Since you should have MinGW-w64 readily available then you can compile the file using windres and link it into your program. If you instead use Visual C++ then look into the Windows Resource Compiler.

The directory structure could look like this:

my-project/
├── icons/
|   ├── application.ico
|   └── window.ico
├── basic.cc
└── resources.rc

resources.rc:

100 ICON "icons\\application.ico"
32512 ICON "icons\\window.ico"

Note: The ID of the icon resource to be used for the window must be 32512 (IDI_APPLICATION).

Compile:

windres -o build/resources.o resources.rc
g++ basic.cc build/resources.o [...]

Remember to bundle the DLLs you have not linked statically, e.g. those from MinGW-w64 and optionally WebView2Loader.dll.

MinGW-w64 Requirements

In order to build this library using MinGW-w64 on Windows then it must support C++17 and have an up-to-date Windows SDK. This applies both when explicitly building the C/C++ library as well as when doing so implicitly through Go/cgo.

Distributions that are known to be compatible:

MS WebView2 Loader

Linking the WebView2 loader part of the Microsoft WebView2 SDK is not a hard requirement when using our webview library, and neither is distributing WebView2Loader.dll with your app.

If, however, WebView2Loader.dll is loadable at runtime, e.g. from the executable's directory, then it will be used; otherwise our minimalistic implementation will be used instead.

Should you wish to use the official loader then remember to distribute it along with your app unless you link it statically. Linking it statically is possible with Visual C++ but not MinGW-w64.

Here are some of the noteworthy ways our implementation of the loader differs from the official implementation:

  • Does not support configuring WebView2 using environment variables such as WEBVIEW2_BROWSER_EXECUTABLE_FOLDER.
  • Microsoft Edge Insider (preview) channels are not supported.

The following compile-time options can be used to change how the library integrates the WebView2 loader:

  • WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL=<1|0> - Enables or disables the built-in implementation of the WebView2 loader. Enabling this avoids the need for WebView2Loader.dll but if the DLL is present then the DLL takes priority. This option is enabled by default.
  • WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK=<1|0> - Enables or disables explicit linking of WebView2Loader.dll. Enabling this avoids the need for import libraries (*.lib). This option is enabled by default if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL is enabled.

Development

To build the library, examples and run tests, run script/build.sh on Unix-based systems and script/build.bat on Windows.

Note: These scripts are not in the best condition but a rewrite is being planned. Please bear with us and manually edit the scripts to your liking.

Limitations

Browser Features

Since a browser engine is not a full web browser it may not support every feature you may expect from a browser. If you find that a feature does not work as expected then please consult with the browser engine's documentation and [open an issue][issues-new] if you think that the library should support it.

For example, the library does not attempt to support user interaction features like alert(), confirm() and prompt() and other non-essential features like console.log().

Go Bindings

Calling Eval() or Dispatch() before Run() does not work because the webview instance has only been configured and not yet started.

Licenses and Copyrights

  • Cross-platform webview library: MIT from webview/webview. Copyright (c) 2017 Serge Zaitsev.
  • Systray is a cross-platform Go library to place an icon and menu in the notification area, with webview support! Apache License 2.0 from ghostiam/systray

Credits

License

Code is distributed under MIT license, feel free to use it in your proprietary projects as well.

Documentation

Index

Constants

View Source
const (
	// Width and height are default size
	HintNone = C.WEBVIEW_HINT_NONE
	// Window size can not be changed by a user
	HintFixed = C.WEBVIEW_HINT_FIXED
	// Width and height are minimum bounds
	HintMin = C.WEBVIEW_HINT_MIN
	// Width and height are maximum bounds
	HintMax = C.WEBVIEW_HINT_MAX

	//--------------------------------------------------------- MacOS Linux Windows
	WindowClose          = C.WEBVIEW_WINDOW_CLOSE          // 0   +     +     +
	WindowFocus          = C.WEBVIEW_WINDOW_FOCUS          // 1   +     +     +
	WindowBlur           = C.WEBVIEW_WINDOW_BLUR           // 2   +     +     +
	WindowMove           = C.WEBVIEW_WINDOW_MOVE           // 3   +     +     +
	WindowResize         = C.WEBVIEW_WINDOW_RESIZE         // 4   +     +     +
	WindowFullScreen     = C.WEBVIEW_WINDOW_FULLSCREEN     // 5   +     +     +
	WindowExitFullScreen = C.WEBVIEW_WINDOW_EXITFULLSCREEN // 6   +     +     +
	WindowMaximize       = C.WEBVIEW_WINDOW_MAXIMIZE       // 7   -     +     +
	WindowUnmaximize     = C.WEBVIEW_WINDOW_UNMAXIMIZE     // 8   -     +     -
	WindowMinimize       = C.WEBVIEW_WINDOW_MINIMIZE       // 9   +     +     +
	WindowUnminimize     = C.WEBVIEW_WINDOW_UNMINIMIZE     // 10  +     +     -

)

Variables

Functions

This section is empty.

Types

type Hint

type Hint int

Hint are used to configure window sizing and resizing

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 properly encoded data.
	// URI. Examples:
	// w.Navigate("https://github.com/webview/webview")
	// w.Navigate("data:text/html,%3Ch1%3EHello%3C%2Fh1%3E")
	// w.Navigate("data:text/html;base64,PGgxPkhlbGxvPC9oMT4=")
	Navigate(url string)

	// SetHtml sets the webview HTML directly.
	// Example: w.SetHtml(w, "<h1>Hello</h1>");
	SetHtml(html string)

	// Init injects JavaScript code at the initialization of the new page. Every
	// time the webview will open a 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

	// SetUserAgent sets a custom user agent string for the webview.
	SetUserAgent(userAgent string)

	// SetWindowEventsHandler sets the window status change event handling function
	// Should be called before calling the "Run" method
	// Example:
	// w.SetWindowEventsHandler("test", func(state webview.WindowState) {
	//		switch state {
	//		case webview.WindowClose:
	//			w.Hide()
	//		case webview.WindowResize:
	//			// Example: save window size for restore in next launch
	//		case webview.WindowMove:
	//			// Example: save window position for restore in next launch
	//		}
	//	})
	SetWindowEventsHandler(key string, f func(state WindowState))

	// UnSetWindowEventsHandler unsets the window status change event handling function
	UnSetWindowEventsHandler(key string)

	// IsExistWindowEventsHandler checks if this event handler exists
	IsExistWindowEventsHandler(key string) bool

	// GetTitle gets the title of the native window.
	GetTitle() string

	// Hide hides the native window.
	Hide()

	// Show shows the native window.
	Show()

	// SetBorderless activates the borderless mode.
	SetBorderless()

	// SetBordered activates the bordered mode.
	SetBordered()

	// IsMaximized If the native window is maximized it returns true, otherwise false.
	IsMaximized() bool

	// Maximize maximizes the native window.
	Maximize()

	// Unmaximize unmaximizes the native window.
	Unmaximize()

	// IsMinimized If the native window is minimized it returns true, otherwise false.
	// IsMinimized Does not work with Stage Manager (MacOS)
	IsMinimized() bool

	// Minimize minimizes the native window.
	Minimize()

	// Unminimize unminimizes the native window.
	Unminimize()

	// IsVisible If the native window is visible it returns true, otherwise false.
	IsVisible() bool

	// SetFullScreen activates the full-screen mode.
	SetFullScreen()

	// ExitFullScreen exits full-screen mode.
	ExitFullScreen()

	// IsFullScreen If the native window is in full-screen mode it returns true, otherwise false.
	IsFullScreen() bool

	// SetIcon sets the application icon (from filename).
	// Example:
	// w.SetIcon("icon.png")
	SetIcon(icon string) error

	// SetIconBites sets the application icon (from []byte).
	// Example:
	// iconData, err = os.ReadFile("icon.png")
	// w.SetIconBites(iconData, len(iconData))
	SetIconBites(b []byte, size int)

	// SetAlwaysOnTop activates (=true) / deactivates(=false) the top-most mode.
	SetAlwaysOnTop(onTop bool)

	// GetSize gets the size of the native window.
	GetSize() (width int, height int, hint Hint)

	// GetPosition gets the coordinates of the native window.
	GetPosition() (x, y int)

	// Move moves the native window to the specified coordinates.
	Move(x, y int)

	// Focus set the focus on the native window.
	Focus()

	// SetContentStateHandler sets the document status change event handling function
	// Should be called before calling the "Run" method
	// Example:
	// w.SetContentStateHandler("test", func(state string) {
	//		fmt.Printf("document content state: %s\n", state)
	// })
	// Status of the document:
	// uninitialized - Has not started loading
	// loading - Is loading
	// loaded - Has been loaded
	// interactive - Has loaded enough to interact with
	// complete - Fully loaded
	SetContentStateHandler(key string, f func(state string))

	// UnSetContentStateHandler unsets the document status change event handling function
	UnSetContentStateHandler(key string)

	// IsExistContentStateHandler checks if this event handler exists
	IsExistContentStateHandler(key string) bool

	// SetDraggable converts a given DOM element to a draggable region. The user will be able to drag the native window by dragging the given DOM element.
	// This feature is suitable to make custom window bars along with the borderless mode.
	SetDraggable(id string)

	// UnSetDraggable converts a draggable region to a normal DOM elements by removing drag event handlers.
	UnSetDraggable(id string)

	// OpenUrlInBrowser Opens the specified link in the web browser
	OpenUrlInBrowser(url string) (err error)

	// Just for an example of using the Bind function. See js.go and init.js
	GetHtml() (s string)
	GetUrl() string
	GetPageTitle() string
}

func New

func New(debug, exitOnClose bool) WebView

New calls NewWindow to create a new window and a new webview instance. If debug is non-zero - developer tools will be enabled (if the platform supports them).

type WindowState

type WindowState int

WindowState used when changing the native window status

Directories

Path Synopsis
examples
pkg
dialog
Package dialog provides a simple cross-platform common dialog API.
Package dialog provides a simple cross-platform common dialog API.
systray
Package systray is a cross-platform Go library to place an icon and menu in the notification area.
Package systray is a cross-platform Go library to place an icon and menu in the notification area.
systray module

Jump to

Keyboard shortcuts

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