@Frutela

Как вызвать функцию из Golang WebView в JavaScript React?

Здравствуйте!

Пред история. Пишу лаунчер. У меня есть Backend часть, которая обрабатывает запросы, есть WebView написанный на Golang с использованием библиотеки "polevpn/webview", есть Frontend часть там используется React с JavaScript.
Я разобрался как можно сделать вызов из JS в Golang WebView, но обратно я не смог разобраться.
Вот функции:
// 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()

	//show webview windows
	Show()

	//hide webview windows
	Hide()

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

	// SetIcon.
	SetIcon(iconBytes []byte)

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


Из всех этих функции я пробовал много чего. Я думал проблема в функции(котоаря внутри JS). Но я даже пытался вызвать console.log
wview.Dispatch(func() {
		wview.Eval(`console.log("Hello from Golang via WebView!");`)
	})


Хочу сказать, что проблема не в библиотеки, я сделал тест прямо в Golang без React написал простенький HTML страницу + JS и попытался всё то же провернуть и она успешно выполнилась.

В App.js я добавил функцию
function receiveHandshake(data) {
    console.log("Received data from Go:", data);
    // Отправьте данные через WebSocket
}


Она так же не вызывается.

Вопрос заключается в том, как можно грамотно это дело обойти и чтобы оно вызывалось? Без всяких костылей и отправка запросов со стороны Desktop приложение.
  • Вопрос задан
  • 210 просмотров
Решения вопроса 1
@Frutela Автор вопроса
Проблему решил обойти "Каллбэком" через функцию Bind. Вопрос закрыт, сам решил проблему.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы