Как вызвать функцию из 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 |
// 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!");`) }) |
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 } |
function receiveHandshake(data) { console.log("Received data from Go:", data); // Отправьте данные через WebSocket }
Она так же не вызывается.
Вопрос заключается в том, как можно грамотно это дело обойти и чтобы оно вызывалось? Без всяких костылей и отправка запросов со стороны Desktop приложение.
Дополнительно:
Советую поместить код в тег для кода, чтобы код стал читабельным, т.к. в таком виде даже не хочется смотреть на него
написал простенький HTML страницу + JS и попытался всё то же провернуть и она успешно выполнилась
У вас был какой-то работающий упрощённый вариант. Потом вы попытались его расширить, чтобы он рабтал с React. Но из этой попытки вы привели только один метод с console.log и говорите, что он "не вызывается". Как вы пытались этот код вызвать?
Проблему решил обойти "Каллбэком" через функцию Bind. Вопрос закрыт, сам решил проблему.
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для вызова функции из Golang WebView в JavaScript React, необходимо использовать механизм межпроцессного взаимодействия (IPC). В данном случае, мы можем использовать механизм вызова JavaScript функций из Go кода с помощью пакета github.com/zserge/webview.
Вот пример кода, демонстрирующий вызов функции из Golang WebView в JavaScript React:
```html
// JavaScript React код
function greetFromGo(message) {
console.log("Message from Go:", message);
}
```
```go
package main
import (
"github.com/zserge/webview"
)
func main() {
webview.Open("WebView Example", "http://localhost:8080", 800, 600, true)
}
func greetToJS(w webview.WebView, data string) {
// Вызываем JavaScript функцию из Go кода
w.Eval(`greetFromGo("` + data + `")`)
}
```
В данном примере, мы создаем простой HTML файл с JavaScript кодом, который содержит функцию greetFromGo, которая будет вызываться из Go кода. Затем, в Go коде, мы используем пакет webview для открытия WebView и вызова JavaScript функции greetFromGo.
Не забудьте запустить свой Go сервер, чтобы обеспечить доступ к HTML файлу по указанному URL. Теперь вы сможете вызывать функцию из Golang WebView в JavaScript React.