webview

package module
v0.0.0-...-4d7953a Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2023 License: MIT Imports: 7 Imported by: 0

README

webview

Build Status GoDoc Go Report Card

A fork of github.com/webview/webview

Webview is a cross-platform library for C/C++/Golang to build modern GUIs.

It uses Cocoa/WebKit on macOS, gtk-webkit2 on Linux and Edge on Windows 10.

Webview for Go developers

Getting started

Install Webview library with go get:

$ go get github.com/LightningDev1/webview

Import the package and start using it:

package main

import "github.com/LightningDev1/webview"

func main() {
	debug := true
	w := webview.New(800, 600, "Minimal webview example", debug)
	defer w.Destroy()
	w.SetIconFromFile("path/to/icon.ico")
	w.Navigate("https://en.m.wikipedia.org/wiki/Main_Page")
	w.Run()
}

To build the app use the following commands:

# Linux
$ go build -o webview-example && ./webview-example

# MacOS uses app bundles for GUI apps
$ mkdir -p example.app/Contents/MacOS
$ go build -o example.app/Contents/MacOS/example
$ open example.app # Or click on the app in Finder

# Windows requires special linker flags for GUI apps.
# It's also recommended to use TDM-GCC-64 compiler for CGo.
# http://tdm-gcc.tdragon.net/download
$ go build -ldflags="-H windowsgui" -o webview-example.exe

For more details see godoc.

Distributing webview apps

On Linux you get a standalone executable. It will depend on GTK3 and GtkWebkit2, so if you distribute your app in DEB or RPM format include those dependencies. An application icon can be specified by providing a .desktop file.

On MacOS you are likely to ship an app bundle. Make the following directory structure and just zip it:

example.app
└── Contents
    ├── Info.plist
    ├── MacOS
    |   └── example
    └── Resources
        └── example.icns

Here, Info.plist is a property list file and *.icns is a special icon format. You may convert PNG to icns online.

On Windows you probably would like to have a custom icon for your executable. It can be done by providing a resource file, compiling it and linking with it. Typically, windres utility is used to compile resources. Also, on Windows, webview.dll and WebView2Loader.dll must be placed into the same directory with your app executable.

NOTE: To use the edge_chromium browser engine (WebView2), you need to have the WebView2 Runtime installed. If you want to prompt the user to install it when they run your app and it isn't installed, call the EnsureWebView2Runtime() function before Run(). If the WebView2 runtime is not installed, it will fallback to the edge_html browser engine.

Webview for C/C++ developers

Download webview.h and include it in your C/C++ code:

C++:
// main.cc
#include "webview.h"
#ifdef WIN32
int WINAPI WinMain(HINSTANCE hInt, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow) {
#else
int main() {
#endif
  webview::webview w(480, 320, "Minimal example", true, nullptr);
  w.navigate("https://en.m.wikipedia.org/wiki/Main_Page");
  w.run();
  return 0;
}

Build it:

# Linux
$ c++ main.cc `pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0` -o webview-example
# MacOS
$ c++ main.cc -std=c++11 -framework WebKit -o webview-example
# Windows (x64)
$ c++ main.cc -mwindows -L./dll/x64 -lwebview -lWebView2Loader -o webview-example.exe
C:
// main .c
#include "webview.h"
#ifdef WIN32
int WINAPI WinMain(HINSTANCE hInt, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow) {
#else
int main() {
#endif
	webview_t w = webview_create(480, 320, "Webview Example", 0, NULL);
	webview_navigate(w, "https://en.m.wikipedia.org/wiki/Main_Page");
	webview_run(w);
	webview_destroy(w);
	return 0;
}

Build it:

# Linux
$ g++ main.c `pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0` -o webview-example
# MacOS
$ g++ main.c -std=c++11 -framework WebKit -o webview-example
# Windows (x64)
$ g++ main.c -mwindows -L./dll/x64 -lwebview -lWebView2Loader -o webview-example.exe

On Windows it is possible to use webview library directly when compiling with cl.exe, but WebView2Loader.dll is still required. To use MinGW you may dynamically link prebuilt webview.dll (this approach is used in Cgo bindings).

Full C/C++ API is described at the top of the webview.h file.

Notes

Execution on OpenBSD requires wxallowed mount(8) option. For Ubuntu Users run sudo apt install webkit2gtk-4.0(Try with webkit2gtk-4.0-dev if webkit2gtk-4.0 is not found) to install webkit2gtk-4.0 related items. FreeBSD is also supported, to install webkit2 run pkg install webkit2-gtk3.

License

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

Documentation

Overview

Example
w := New(480, 320, "Test", true)
defer w.Destroy()
w.Navigate("https://google.com/")
w.Bind("noop", func() string {
	log.Println("hello")
	return "hello"
})
w.Bind("add", func(a, b int) int {
	return a + b
})
w.Bind("quit", func() {
	w.Terminate()
})
w.Navigate(`data:text/html,
		<!doctype html>
		<html>
			<body>hello</body>
			<script>
				window.onload = function() {
					document.body.innerText = ` + "`hello, ${navigator.userAgent}`" + `;
					noop().then(function(res) {
						console.log('noop res', res);
						add(1, 2).then(function(res) {
							console.log('add res', res);
							quit();
						});
					});
				};
			</script>
		</html>
	)`)
w.Run()
Output:

Index

Examples

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
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Hint

type Hint int

Hints 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

	// Show shows the window when it's hidden
	Show()

	// Hide hides the webview window
	Hide()

	// Minimize the window
	Minimize()

	// Maximize the window
	Maximize()

	// HideToSystemTray hides the window to the system tray. The window will be shown
	// again when the icon in the system tray is clicked. You must call SetIcon or
	// SetIconFromFile before using this as it won't work without an icon.
	// This only works on Windows.
	HideToSystemTray()

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

	// SetIcon sets the window icon
	SetIcon(iconBytes []byte)

	// SetIcon sets the window icon
	SetIconFromFile(iconFile string)

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

	// 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

	// Create the JS SendEvent function that will callback to Go with eventName and eventData (JSON) so
	// we can use non-web stuff like creating or reading files. A FILE_READ example event is supplied,
	// you can add events like how it's shown there.
	// Usage in JavaScript:
	// window.SendEvent("FILE_READ", JSON.stringify({
	// 	file: "some_file.txt",
	// 	base64: false
	// })).then(data => {
	// 	const JsonData = JSON.parse(data);
	// 	if (JsonData.error) {
	// 		return console.error("An error has occurred: " + JsonData.message);
	// 	}
	// 	console.log("File Contents: " + JsonData["fileContents"]);
	// });
	InitMessageHandler()

	// Add a message handler. Must first call InitMessageHandler().
	AddMessageHandler(eventName string, f func(message string, messageData string) string)

	// Send a message event to javascript. You can use it with this code in JS:
	// window.addEventListener("webview_message", (eventName, eventData) => {
	//     console.log(eventName);
	//     console.log(eventData);
	// });
	SendMessage(eventName string, eventData string)
}

func New

func New(width int, height int, title string, debug 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).

func NewWindow

func NewWindow(width int, height int, title string, debug bool, window unsafe.Pointer) WebView

NewWindow creates a new webview instance. If debug is non-zero - developer tools will be enabled (if the platform supports them). Window parameter can be a pointer to the native window handle. If it's non-null - then child WebView is embedded into the given parent window. Otherwise a new window is created. Depending on the platform, a GtkWindow, NSWindow or HWND pointer can be passed here.

Jump to

Keyboard shortcuts

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