Giter Site home page Giter Site logo

webview_go's Introduction

webview

Discord Build Status

A tiny cross-platform webview library for C/C++ 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 C/C++ and to call C/C++ from JavaScript).

Note

Language binding for Go has moved. Versions <= 0.1.1 are available in this repository.

Platform Support

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

Documentation

The most up-to-date documentation is right in the source code. Improving the documentation is a continuous effort and you are more than welcome to contribute.

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++14 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 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.

C/C++ Preparation

Fetch the webview library:

curl -sSLo "libs/webview/webview.h" "https://raw.githubusercontent.com/webview/webview/master/webview.h"
curl -sSLo "libs/webview/webview.cc" "https://raw.githubusercontent.com/webview/webview/master/webview.cc"

Getting Started with C++

Save the basic C++ example into your project directory:

curl -sSLo basic.cc "https://raw.githubusercontent.com/webview/webview/master/examples/basic.cc"

Build and run the example:

# Linux
g++ basic.cc -std=c++11 -Ilibs/webview $(pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0) -o build/basic && ./build/basic
# macOS
g++ basic.cc -std=c++11 -Ilibs/webview -framework WebKit -o build/basic && ./build/basic
# Windows/MinGW
g++ basic.cc -std=c++14 -mwindows -Ilibs/webview -Ilibs/webview2/build/native/include -ladvapi32 -lole32 -lshell32 -lshlwapi -luser32 -lversion -o build/basic.exe && "build/basic.exe"

Bonus for Visual C++

Build a C++ example:

cl basic.cc /std:c++14 /EHsc /Fobuild\ ^
    /I libs\webview ^
    /I libs\webview2\build\native\include ^
    /link /OUT:build\basic.exe

Getting Started with C

Save the basic C example into your project directory:

curl -sSLo basic.c "https://raw.githubusercontent.com/webview/webview/master/examples/basic.c"

Build the library and example, then run it:

# Linux
g++ -c libs/webview/webview.cc -std=c++11 -DWEBVIEW_STATIC $(pkg-config --cflags gtk+-3.0 webkit2gtk-4.0) -o build/webview.o
gcc -c basic.c -std=c99 -Ilibs/webview -o build/basic.o
g++ build/basic.o build/webview.o $(pkg-config --libs gtk+-3.0 webkit2gtk-4.0) -o build/basic && build/basic
# macOS
g++ -c libs/webview/webview.cc -std=c++11 -DWEBVIEW_STATIC -o build/webview.o
gcc -c basic.c -std=c99 -Ilibs/webview -o build/basic.o
g++ build/basic.o build/webview.o -framework WebKit -o build/basic && build/basic
# Windows/MinGW
g++ -c libs/webview/webview.cc -std=c++14 -DWEBVIEW_STATIC -Ilibs/webview2/build/native/include -o build/webview.o
gcc -c basic.c -std=c99 -Ilibs/webview -o build/basic.o
g++ build/basic.o build/webview.o -mwindows -ladvapi32 -lole32 -lshell32 -lshlwapi -luser32 -lversion -o build/basic.exe && "build/basic.exe"

Bonus for Visual C++

Build a shared library:

cl libs\webview\webview.cc /std:c++14 /EHsc /Fobuild\ ^
    /D WEBVIEW_BUILD_SHARED ^
    /I libs\webview ^
    /I libs\webview2\build\native\include ^
    /link /DLL /OUT:build\webview.dll

Build a C example using the shared library:

cl basic.c build\webview.lib /EHsc /Fobuild\ ^
    /D WEBVIEW_SHARED ^
    /I libs\webview ^
    /link /OUT:build\basic.exe

More Examples

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

Compile-time Options

C API Linkage

Name Description
WEBVIEW_API Controls C API linkage, symbol visibility and whether it's a shared library. By default this is inline for C++ and extern for C.
WEBVIEW_BUILD_SHARED Modifies WEBVIEW_API for building a shared library.
WEBVIEW_SHARED Modifies WEBVIEW_API for using a shared library.
WEBVIEW_STATIC Modifies WEBVIEW_API for building or using a static library.

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++14 and have an up-to-date Windows SDK.

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, use one of the builds scripts in the script directory:

  • build.sh:

    • On Unix-based systems.
    • On Windows in a Unix-like environment such as MSYS2.
  • build.bat:

    • On Windows when building with Visual C++.

You can specify individual tasks on the command line for these scripts:

Task Description
info Displays information.
clean Cleans the build directory.
format Reformats code.
deps Fetches dependencies.
check Runs checks.
build Builds the library, examples and tests.
test Runs tests.

Additionally, the scripts accept the following environment variables.

Both scripts:

Variable Description
CI Changes behavior in CI environments (more strict).
TARGET_ARCH Target architecture for cross-compilation (x64, x86).
BUILD_DIR Overrides the path of the build directory.

Only build.sh:

Variable Description
HOST_OS Host operating system (linux, macos, windows).
TARGET_OS Target operating system for cross-compilation (see HOST_OS).
CC C compiler executable.
CXX C++ compiler executable.
LIB_PREFIX Library name prefix.
PKGCONFIG Alternative pkgconfig executable.

Cross-compilation

See the CI configuration for examples.

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 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().

Bindings

Language Project
Bun tr1ckydev/webview-bun
C# webview/webview_csharp
C3 thechampagne/webview-c3
Crystal naqvis/webview
D thechampagne/webview-d
Deno webview/webview_deno
Go webview/webview_go
Harbour EricLendvai/Harbour_WebView
Haskell lettier/webviewhs
Janet janet-lang/webview
Java webview/webview_java
Kotlin Winterreisender/webviewko
Nim oskca/webview, neroist/webview
Node.js Winterreisender/webview-nodejs
Odin thechampagne/webview-odin
Pascal PierceNg/fpwebview
Python zserge/webview-python
PHP 0hr/php-webview
Ruby Maaarcocr/webview_ruby
Rust Boscop/web-view
Swift jakenvac/SwiftWebview
V malisipi/mui, ttytm/webview
Zig thechampagne/webview-zig

If you wish to add bindings to the list, feel free to submit a pull request or open an issue.

Generating Bindings

You can generate bindings for the library by yourself using the included SWIG interface (webview.i).

Here are some examples to get you started. Unix-style command lines are used for conciseness.

mkdir -p build/bindings/{python,csharp,java,ruby}
swig -c++ -python -outdir build/bindings/python -o build/bindings/python/python_wrap.cpp webview.i
swig -c++ -csharp -outdir build/bindings/csharp -o build/bindings/csharp/csharp_wrap.cpp webview.i
swig -c++ -java -outdir build/bindings/java -o build/bindings/java/java_wrap.cpp webview.i
swig -c++ -ruby -outdir build/bindings/ruby -o build/bindings/ruby/ruby_wrap.cpp webview.i

License

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

webview_go's People

Contributors

nothingismagick avatar steffenl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webview_go's Issues

Navigate response headers

this program works:

package main

import "github.com/webview/webview_go"

func main() {
   w := webview.New(false)
   defer w.Destroy()
   w.Navigate("http://example.com")
   w.Run()
}

but how can I get the response headers from the Navigate?

`destroy` is not working

Doc: // Destroys a webview and closes the native window.

package main

import "github.com/webview/webview_go"

const html = `<html style="background: #1B2845; color: #eee;">
<button onclick="window.exit();">Exit</button>
</html>`

func main() {
	w := webview.New(true)
	w.SetTitle("Bind Example")
	w.SetSize(480, 320, webview.HintNone)

	w.Bind("exit", func() {
		w.Dispatch(func() {
			w.Destroy()
			// w.Terminate() // Works. But I'd like to keep the main loop.
			println("Should be destroyed.")
		})
	})

	w.SetHtml(html)
	w.Run()
}
gcc (GCC) 13.2.1 20230801
clang version 16.0.6
go version go1.21.0 linux/amd64

Compilation prompts missing files

`
PS D:\gitee.com\go\go-webview> go build -ldflags="-H windowsgui"

github.com/webview/webview_go

In file included from D:/goRely/goPath/pkg/mod/github.com/webview/[email protected]/libs/webview/include/webview.h:2076,
from webview.cc:1:
D:/goRely/goPath/pkg/mod/github.com/webview/[email protected]/libs/mswebview2/include/WebView2.h:978:10: fatal error: EventToken.h: No such file or directory
#include "EventToken.h"
^~~~~~~~~~~~~~
compilation terminated.
PS D:\gitee.com\go\go-webview>
`

gcc version 8.1.0 (x86_64-posix-sjlj-rev0, Built by MinGW-W64 project)

How to hide the window without destroying it.

Is there a way to show/hide the webview without destroying and recreating it? I would like an icon in the taskbar (like lantern systray) that when I click it, the webview ui shows or hides. I don't want to destroy it each time. Just make it invisible.

compilation error

os: windows 10
go: 1.22

I used to compile normally. An error is being thrown now:

CGO_ENABLED=0:
github.com/webview/webview_goback build restrictions exclude all Go files in C:\Users\root\go\pkg\mod\git
hub.com\webview\[email protected]

CGO_ENABLED=1:
|# github.com/webview/webview_go
In the file included from C:/Users/root/go/pkg/mod/github.com/webview/[email protected]
f456ca3a43/libs/webview/include/webview.h:2076,
from webview.cc:1:
C:/Users/root/go/pkg/mod/github.com/webview/[email protected]/libs/mswebv
iew2/include/WebView 2.h:978:10: fatal error: The event token.h: There is no such file or directory
978 | #include "EventToken.h"
| ^~~~~~~~~~~~~~
compilation is complete.

Cannot create new window after destroy

Hi-

My program creates a webview, and displays some html successfully. I have seen two bad behaviors:

  • If the content is not good HTML, then closing the window causes a SEGV
  • If the content is good HTML, closing the window is fine, but the next window I create causes a SEGV

I need to be able to create/destroy webview windows many times during my application. Is this possible?

Webview is constrained to just one function in my code, and is taken right from an example:

func displayEmail(txt string) {
// open a viewport and view it
w := webview.New(false)
defer w.Destroy()
w.SetTitle("Email View")
w.SetSize(480, 320, webview.HintNone)
w.SetHtml(txt)
w.Run()
}

Build webview linux for windows

GOOS=windows GOARCH=amd64 go build -ldflags="-H windowsgui" main.go

but error why ?

github.com/webview/webview_go: build constraints exclude all Go files in /home/go/pkg/mod/github.com/webview/[email protected]

[bug] After launching the window, the methods ( "Navigation", "SetHtml") do not work

I needed to change the page address or apply html code, but after launching the main window, these methods ( "Navigation", "setHtml") no longer work. Nothing happens after they are called.
`

w := webview.New(false)
defer w.Destroy()

w.SetSize(800, 600, webview.HintNone)
w.Navigate("https://example.com")

go func() {
	for {
		w.Navigate("https://google.com")

		time.Sleep(5 * time.Second)
	}
}()

w.Run()

`

system_os: Windows 10
go_version: 1.19

#include "EventToken.h" error

github.com/webview/webview_go

In file included from C:/Users/26225/go/pkg/mod/github.com/webview/[email protected]/libs/webview/include/webview.h:1132,
from webview.cc:1:
C:/Users/26225/go/pkg/mod/github.com/webview/[email protected]/libs/mswebview2/include/WebView2.h:978:10: fatal error: EventToken.h: No such file or directory
#include "EventToken.h"
^~~~~~~~~~~~~~
compilation terminated.

go version go1.20.11 windows/amd64
What should I do

fatal error: EventToken.h: No such file or directory

Parallels + win10

gcc --version

gcc.exe (tdm64-1) 10.3.0

g++ --version

g++.exe (tdm64-1) 10.3.0

mingw32-make --version

GNU Make 3.82.90
Built for i686-pc-mingw32
Copyright (C) 1988-2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Fullscreen support requested

Hello,

In the now depricated version of the webview bindings for go there was also support for turning the window full screen.
To my surprise this feature is not implemented in this version.
I'd love to see this feature re-introduced.

w.SetFullscreen(true)

Android support planned?

Hello! I'd like to know if there's planned support for Android, since android have a native webview package starting from Android 6.

Investigate documentation stating Dispatch normally need not be called

@Le0Developer pointed out in #26 that Dispatch might need clarification when I suggested that Dispatch should be called.

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

We should investigate whether this comment is accurate, and either amend it or fix the behavior.

Can't get code to compile

I finally figured out that my Go project was failing due to the bindings being moved to webview_go... But I now have no idea what to do with the following message.

Are there any new docs still in the works? Please advise...

../../../go/pkg/mod/github.com/webview/[email protected]/libs/webview/include/webview.h: In member function ‘void webview::detail::gtk_webkit_engine::eval(const string&)’:
../../../go/pkg/mod/github.com/webview/[email protected]/libs/webview/include/webview.h:617:35: warning: ‘void webkit_web_view_run_javascript(WebKitWebView*, const gchar*, GCancellable*, GAsyncReadyCallback, gpointer)’ is deprecated: Use 'webkit_web_view_evaluate_javascript' instead [-Wdeprecated-declarations]
  617 |     webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js.c_str(),
      |     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  618 |                                    nullptr, nullptr, nullptr);
      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/webkitgtk-4.0/webkit/WebKitPrintOperation.h:29,
                 from /usr/include/webkitgtk-4.0/webkit2/webkit2.h:72,
                 from ../../../go/pkg/mod/github.com/webview/[email protected]/libs/webview/include/webview.h:510,
                 from webview.cc:1:
/usr/include/webkitgtk-4.0/webkit/WebKitWebView.h:526:1: note: declared here
  526 | webkit_web_view_run_javascript                       (WebKitWebView             *web_view,
      | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Can not build: Build constraints exclude all Go files

can not build when running the command GOOS=darwin GOARCH=amd64 go build

error: github.com/webview/webview_go: build constraints exclude all Go files in /Users/pritishmishra/go/pkg/mod/github.com/webview/[email protected]

but the go build command works. if I do this go build .

my go env:

GO111MODULE=''
GOARCH='arm64'
GOBIN=''
GOCACHE='/Users/pritishmishra/Library/Caches/go-build'
GOENV='/Users/pritishmishra/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='arm64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMODCACHE='/Users/pritishmishra/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/pritishmishra/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/darwin_arm64'
GOVCS=''
GOVERSION='go1.22.1'
GCCGO='gccgo'
AR='ar'
CC='clang'
CXX='clang++'
CGO_ENABLED='1'
GOMOD='/Users/pritishmishra/Documents/Projects/sql-editor/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/60/92p0hs5x0v5fsfw5hfmpwbm80000gn/T/go-build4183224487=/tmp/go-build -gno-record-gcc-switches -fno-common'

go version: go version go1.22.1 darwin/arm64
g++ version: Apple clang version 15.0.0 (clang-1500.3.9.4) Target: arm64-apple-darwin23.4.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Loading scripts and styles from files inside <script> and <link>

pretty straight forward. I have the following HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #root {
            max-width: 1280px;
            margin: 0 auto;
            padding: 2rem;
            text-align: center;
            background-color: #1f1f0f;
        }
    </style>
</head>
<body>
<div id="root">
    <p id="item"></p>
    <button>yes</button>
</div>
<script>
    document.getElementById("item").innerHTML = "generated content"
</script>
</body>
</html>

The output window is working as expected, showing the styles and the generated text inside the <p> tag.

however, if the script and styles were in files like this:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script type="module" src="index.js"></script>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="root">
    <p id="item"></p>
    <button>yes</button>
</div>
</body>
</html>

Both the script and styles do not take effect. couldn't find a solution or anyone talking about it.
is there a solution? thanks in advance.

I am on windows 10, go 1.20

not able to use go run

I updated and now using go run fails:

# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running g++ failed: exit status 1
/usr/bin/ld: /tmp/go-link-598592747/000003.o: undefined reference to symbol 'dlclose@@GLIBC_2.2.5'
/usr/bin/ld: /lib/x86_64-linux-gnu/libdl.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

using go build and then running the binary still works tho

编译报错

GOOS=linux GOARCH=amd64 go build -o myapp-loong64 -ldflags "-s -w" main.go
编译报错误:
Stderr: go build github.com/webview/webview_go: build constraints exclude all Go files in

segfault running webview.Eval in goroutine a lot

Ran into this segfault when my app did an oopsie and recursively called a binding that spawned a goroutine which eval'ed itself.

package main

import (
	"fmt"

	webview "github.com/webview/webview_go"
)

func main() {
	w := webview.New(true)
	defer w.Destroy()
	w.SetTitle("Basic Example")
	w.SetSize(480, 320, webview.HintNone)
	w.SetHtml("<button onclick=\"exec()\">Click</button>")
	dept := 0
	w.Bind("exec", func() {
		go func() {
			fmt.Println("exec", dept)
			dept++
			// w.Dispatch(func() {
				w.Eval("setTimeout(window.exec, 1)")
			// })
		}()
	})
	w.Run()
}

Works

  1. without go func() {
  2. with w.Dispatch(func() {

Crash log:

Long log
exec 604
SIGSEGV: segmentation violation
PC=0x188041420 m=5 sigcode=2
signal arrived during cgo execution

goroutine 628 [syscall]:
runtime.cgocall(0x1049b7b30, 0x14000127ed8)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/cgocall.go:157 +0x44 fp=0x14000127ea0 sp=0x14000127e60 pc=0x10
49004c4
github.com/webview/webview_go._Cfunc_webview_eval(0x600000320000, 0x600002046f80)
        _cgo_gotypes.go:162 +0x30 fp=0x14000127ed0 sp=0x14000127ea0 pc=0x1049b5820
github.com/webview/webview_go.(*webview).Eval.func2(0x1049c0a62?, 0x1a?)
        /Users/leodev/go/pkg/mod/github.com/webview/[email protected]/webview.go:199 +0x50 fp
=0x14000127f10 sp=0x14000127ed0 pc=0x1049b6390
github.com/webview/webview_go.(*webview).Eval(0x104a0a1c8?, {0x1049c0a62?, 0x14000127fa8?})
        /Users/leodev/go/pkg/mod/github.com/webview/[email protected]/webview.go:199 +0x68 fp
=0x14000127f60 sp=0x14000127f10 pc=0x1049b62e8
main.main.func1.1()
        /Users/leodev/p/go/main.go:21 +0xb8 fp=0x14000127fd0 sp=0x14000127f60 pc=0x1049b7928
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x14000127fd0 sp=0x14000127fd0 pc=0x1
0495db24
created by main.main.func1 in goroutine 1
        /Users/leodev/p/go/main.go:17 +0x9c

goroutine 1 [syscall, locked to thread]:
runtime.cgocall(0x1049b7bb0, 0x14000117e58)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/cgocall.go:157 +0x44 fp=0x14000117e20 sp=0x14000117de0 pc=0x10
49004c4
github.com/webview/webview_go._Cfunc_webview_run(0x600000320000)
        _cgo_gotypes.go:233 +0x30 fp=0x14000117e50 sp=0x14000117e20 pc=0x1049b5940
github.com/webview/webview_go.(*webview).Run.func1(0x60000222c650?)
        /Users/leodev/go/pkg/mod/github.com/webview/[email protected]/webview.go:157 +0x40 fp
=0x14000117e90 sp=0x14000117e50 pc=0x1049b5e20
github.com/webview/webview_go.(*webview).Run(0x1400004a020?)
        /Users/leodev/go/pkg/mod/github.com/webview/[email protected]/webview.go:157 +0x1c fp
=0x14000117eb0 sp=0x14000117e90 pc=0x1049b5dbc
main.main()
        /Users/leodev/p/go/main.go:25 +0x16c fp=0x14000117f30 sp=0x14000117eb0 pc=0x1049b776c
runtime.main()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:267 +0x2bc fp=0x14000117fd0 sp=0x14000117f30 pc=0x1049
3157c
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x14000117fd0 sp=0x14000117fd0 pc=0x1
0495db24

goroutine 2 [force gc (idle)]:
runtime.gopark(0x0?, 0x0?, 0x0?, 0x0?, 0x0?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:398 +0xc8 fp=0x14000046f90 sp=0x14000046f70 pc=0x10493
19a8
runtime.goparkunlock(...)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:404
runtime.forcegchelper()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:322 +0xb8 fp=0x14000046fd0 sp=0x14000046f90 pc=0x10493
1838
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x14000046fd0 sp=0x14000046fd0 pc=0x1
0495db24
created by runtime.init.6 in goroutine 1
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:310 +0x24

goroutine 18 [GC sweep wait]:
runtime.gopark(0x0?, 0x0?, 0x0?, 0x0?, 0x0?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:398 +0xc8 fp=0x14000042760 sp=0x14000042740 pc=0x10493
19a8
runtime.goparkunlock(...)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:404
runtime.bgsweep(0x0?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgcsweep.go:280 +0xa0 fp=0x140000427b0 sp=0x14000042760 pc=0x1
0491eb50
runtime.gcenable.func1()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgc.go:200 +0x28 fp=0x140000427d0 sp=0x140000427b0 pc=0x104913
648
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x140000427d0 sp=0x140000427d0 pc=0x1
0495db24
created by runtime.gcenable in goroutine 1
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgc.go:200 +0x6c

goroutine 19 [GC scavenge wait]:
runtime.gopark(0x1400008e000?, 0x1049e4550?, 0x1?, 0x0?, 0x140000824e0?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:398 +0xc8 fp=0x14000042f50 sp=0x14000042f30 pc=0x10493
19a8
runtime.goparkunlock(...)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:404
runtime.(*scavengerState).park(0x104aa1640)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgcscavenge.go:425 +0x5c fp=0x14000042f80 sp=0x14000042f50 pc=
0x10491c3fc
runtime.bgscavenge(0x0?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgcscavenge.go:653 +0x44 fp=0x14000042fb0 sp=0x14000042f80 pc=
0x10491c954
runtime.gcenable.func2()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgc.go:201 +0x28 fp=0x14000042fd0 sp=0x14000042fb0 pc=0x104913
5e8
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x14000042fd0 sp=0x14000042fd0 pc=0x1
0495db24
created by runtime.gcenable in goroutine 1
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mgc.go:201 +0xac

goroutine 3 [finalizer wait]:
runtime.gopark(0x140000465c8?, 0x104996c10?, 0x0?, 0x0?, 0x1049bd990?)
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/proc.go:398 +0xc8 fp=0x14000046580 sp=0x14000046560 pc=0x10493
19a8
runtime.runfinq()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mfinal.go:193 +0x108 fp=0x140000467d0 sp=0x14000046580 pc=0x10
49126f8
runtime.goexit()
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/asm_arm64.s:1197 +0x4 fp=0x140000467d0 sp=0x140000467d0 pc=0x1
0495db24
created by runtime.createfing in goroutine 1
        /opt/homebrew/Cellar/go/1.21.6/libexec/src/runtime/mfinal.go:163 +0x80

r0      0x600001522dc0
r1      0x1d767a60e
r2      0x600001522dc0
r3      0x2
r4      0x4
r5      0xf60
r6      0x60000204c860
r7      0x0
r8      0xde9932f2dc0
r9      0xcb850001df096060
r10     0x6ae1600001522dc0
r11     0x1dec053bf
r12     0x0
r13     0x1ff800
r14     0xde9932f2dc0
r15     0xde9932f2dc0
r16     0xde9932f2dc0
r17     0x1e7cb24c8
r18     0x0
r19     0x16d522800
r20     0x600002e2e3a0
r21     0x600001522dc0
r22     0x600001522dc0
r23     0x1540802d0
r24     0x154108200
r25     0x154004200
r26     0x154100aa0
r27     0x29
r28     0x3
r29     0x16d5227f0
lr      0x18861ca3c
sp      0x16d522790
pc      0x188041420
fault   0xde9932f2dd0
exit status 2

error while running main on Mac M1

This is the output:

# github.com/webview/webview_go
vendor/github.com/webview/webview_go/webview.go:16:10: fatal error: 'webview.h' file not found
#include "webview.h"
         ^~~~~~~~~~~
1 error generated.

Do I need to install something extra?

Execution order on Windows is weird

The execution order on Windows is weird.

Example 1

package main

import (
	"fmt"

	webview "github.com/webview/webview_go"
)

func main() {
	view := webview.New(true)
	defer view.Destroy()
	view.SetTitle("Basic Example")
	view.SetSize(480, 320, webview.HintNone)
	view.SetHtml("<script>window.hello()</script>")
	view.Bind("hello", func() {
		fmt.Println("hello from js!")
	})
	view.Run()
}

For some reason the script appears to be executing early, because it can't find the window.hello() binding and errors.
This is not happening on macOS.

Example 2

Also in this example the second view.Init script just doesn't execute at all.

package main

import (
	"fmt"

	webview "github.com/webview/webview_go"
)

func main() {
	view := webview.New(true)
	defer view.Destroy()
	view.SetTitle("Basic Example")
	view.SetSize(480, 320, webview.HintNone)
	view.Init("console.log('init 1', window.hello)")
	view.SetHtml("<script>console.log('js', window.hello);setTimeout(() => console.log('js after 100ms', window.hello), 100)</script>")
	view.Bind("hello", func() {})
	view.Init("console.log('init 2', window.hello)")
	view.Run()
}
Windows macOS
image image

Navigate() also works

The same can be reproduced with Navigate by replacing SetHtml(" with Navigate("data:text/html,.

Window exists before Run()

See this basic example:

package main

import (
	"time"

	webview "github.com/webview/webview_go"
)

func main() {
	view := webview.New(true)
	defer view.Destroy()
	time.Sleep(10 * time.Second)
	view.Run()
}

When running this on macOS the webview appears in the dock but no window is visible for 10s.
However on Windows, a window pops up immediately but it's frozen for 10seconds.

Conclusion

SetHtml/Navigate interact weirdly on Windows. They appear to be starting immediately or earlier than .Run().

examples/basic: Blank screen

git clone https://github.com/webview/webview_go
cd webview_go/examples/basic/
go run main.go

System: go version go1.21.4 linux/amd64

The cursor changes when I hover over where the text is supposed to be, but otherwise its just a blank white screen. In a VM (go version go1.21.4 linux/amd64) it works fine. Has anyone an idea what the issue could be?

I tried to use webview.New(true) in hopes of some helpful logs, but only get this:

# github.com/webview/webview_go
In file included from webview.cc:1:
../../libs/webview/include/webview.h: In member function ‘void webview::detail::gtk_webkit_engine::eval(const std::string&)’:
../../libs/webview/include/webview.h:617:35: warning: ‘void webkit_web_view_run_javascript(WebKitWebView*, const gchar*, GCancellable*, GAsyncReadyCallback, gpointer)’ is deprecated: Use 'webkit_web_view_evaluate_javascript' instead [-Wdeprecated-declarations]
  617 |     webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js.c_str(),
      |     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  618 |                                    nullptr, nullptr, nullptr);
      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/webkitgtk-4.0/webkit/WebKitPrintOperation.h:29,
                 from /usr/include/webkitgtk-4.0/webkit2/webkit2.h:74,
                 from ../../libs/webview/include/webview.h:510:
/usr/include/webkitgtk-4.0/webkit/WebKitWebView.h:526:1: note: declared here
  526 | webkit_web_view_run_javascript                       (WebKitWebView             *web_view,
      | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Overriding existing handler for signal 10. Set JSC_SIGNAL_FOR_GC if you want WebKit to use a different signal

The helloworld wails app worked fine though:
https://wails.io/docs/tutorials/helloworld/

Rare segfault when using eval in dispatch

I am encountering a segfault very inconsistently and rarely right after calling Evaluate in a Dispatch callback.

I have following code that gets run from a separate goroutine from the main thread which called webview.Run():

func (ui *UI) eval(code string) {
	if ui.app.options.Verbose {
		fmt.Println("Eval:", code)
	}
	ui.webview.Dispatch(func() {
		wui.webview.Eval(code)
	})
}

Sometimes this segfaults in the main thread:

Eval: {valid js code}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x102f9c1b0]

goroutine 1 [running, locked to thread]:
github.com/webview/webview_go._webviewDispatchGoCallback(0x5)
	/go/pkg/mod/github.com/webview/webview_go@v0.0.0-20230901181450-5a14030a9070/webview.go:217 +0x120
github.com/webview/webview_go._Cfunc_webview_run(0x6000012d8000)
	_cgo_gotypes.go:237 +0x30
github.com/webview/webview_go.(*webview).Run.func1(0x6000031e4900?)
	/go/pkg/mod/github.com/webview/webview_go@v0.0.0-20230901181450-5a14030a9070/webview.go:157 +0x40
github.com/webview/webview_go.(*webview).Run(0x1400019a0b0?)
	/go/pkg/mod/github.com/webview/webview_go@v0.0.0-20230901181450-5a14030a9070/webview.go:157 +0x1c
app/src.(*WebviewUII).run(0x1400019c1c8)
	app/src/ui_webview.go:40 +0x358
app/src/ui_webview.go:40 +0x358app/src.(*App).Run(0x140001e6180)
	app/src/app.go:41 +0x34
main.main()
	app/main.go:47 +0x4e0
exit status 2

The evaluate is triggered in response to a binding, it's basically:

webview.Bind("rpc", func() {
  go func() {
    app.ui.eval("rpcResponse(42)")
  }()
})

I wrote my own RPC wrapper on top of the one provided because some calls do network requests and thus need to be ran in a goroutine or it'd block the entire UI.

I've been able to reproduce this inconsistently on macOS (MBA, M2) and on Windows 10.
The chance of this segfault is like 0.1%, I have never been able to cause it on purpose, only during normal usage.


Please let me know if you need any further information, or know any launch options I could use to gather more information.

compilation error

C:/Users/26225/go/pkg/mod/github.com/webview/[email protected]/libs/mswebview2/include/WebView2.h:978:10: fatal error: EventToken.h: No such file or directory
#include "EventToken.h"
^~~~~~~~~~~~~~
compilation terminated.

go1.20.11 windows/amd64

Updating webkit2gtk

Since this is a new module, would it be possible to update webkit2gtk to version 4.1 and replace the deprecated webkit_web_view_run_javascript with webkit_web_view_evaluate_javascript?

example appears as blank

when i run the example i get this:

image

I can sort-of drag the text around and see it in the drag. can't really get a screenshot of that, but it shows the content is loading (and if i click in the right place, it increments). But nothing is visible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.