'Javascript functions not working in webview window
I am new to the web frontend approach. Hence, when you need more information please ask.
I have an app with a go backend and a html/css/js frontend, which works rather nicely. Recently, I attempted to transition to webview, which also worked fine with respect to the html and css part. However, my javascript functions do not work and I am quite at a loss as to how to troubleshoot the problem.
Here is a self contained, minimal example, which demonstrates the issue. The webview window opens and displays the title and the button. However clicking the button will not open the alert dialog.
Any hints pointing me in the right direction are highly appreciated.
package main
import (
"github.com/webview/webview"
"html/template"
"net/http"
)
type DummyData struct {
PageTitle string
}
func main() {
go start()
w := webview.New(true)
defer w.Destroy()
w.SetTitle("Test webview")
w.SetSize(800, 600, webview.HintNone)
w.Navigate("http://localhost:80")
w.Run()
}
func start() {
tmpl, _ := template.New("lala").Parse("<!DOCTYPE html><body><h1>{{.PageTitle}}</h1><button onclick=\"myFunction()\">Try it</button><script>function myFunction() {alert(\"js working\");}</script></body>\n</html>")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := DummyData{
PageTitle: "My webview page title",
}
tmpl.Execute(w, data)
})
http.ListenAndServe(":80", nil)
}
Solution 1:[1]
Actually your JS functions do work, just the alert doesn't. Not exactly sure why, but I would supect that alert, confirm and prompt won't get much love anymore.
This here works:
package main
import (
"html/template"
"net/http"
"github.com/webview/webview"
)
type DummyData struct {
PageTitle string
}
func main() {
go start()
w := webview.New(true)
defer w.Destroy()
w.SetTitle("Test webview")
w.SetSize(800, 600, webview.HintNone)
w.Navigate("http://localhost:8000")
w.Run()
}
func start() {
const page = `
<!DOCTYPE html>
<body>
<h1>
{{.PageTitle}}
</h1>
<button onclick="myFunction()">Try it</button>
<div id="d1" hidden>
poor man's alert
</div>
<script>
function myFunction() {
d1.hidden = !d1.hidden
// alert("js working");
}
</script>
</body>
</html>
`
tmpl, _ := template.New("lala").Parse(page)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := DummyData{
PageTitle: "My webview page title",
}
tmpl.Execute(w, data)
})
http.ListenAndServe(":8000", nil)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dirkk0 |
