syscall/js
syscall/js
js.ValueGetSetIndexSetIndexInvokeCall
js.Valuejs.Undefinedjs.Nulljs.Global
Hello, WebAssembly!
<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8">
<title>Go wasm</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
WebAssembly API 等... 略
</script>
<button onClick="run();" id="runButton" disabled>Run</button>
<div id="c1">Hello, WebAssembly!</div>
</body>
</html>
innerHTML
package main
import "syscall/js"
func main() {
window := js.Global() // 获取全局的 window
doc := window.Get("document") // 相当于 window.document
c1 := doc.Call("getElementById", "c1") // 相当于 document.getElementById('c1')
innerHTML := c1.Get("innerHTML").String() // 相当于 c1.innerHTML
println(innerHTML)
}
这边特意使用数个变量,代逐一对照获取的各是哪个 JavaScript 值,实际上当然可以直接写成底下:
package main
import "syscall/js"
func main() {
innerHTML :=
js.Global().
Get("document").
Call("getElementById", "c1").
Get("innerHTML").
String()
println(innerHTML)
}
document.getElementById("c1").innerHTMLc1innerHTML
alert
package main
import "syscall/js"
func main() {
alert := js.Global().Get("alert")
// 相当于 alert('Hello, WebAssembly!')
alert.Invoke("Hello, WebAssembly!")
}
在编译为 WebAssembly、使用浏览器连线至网页之后,按下 Run 按钮,会令浏览器出现警告对话框:
因此,如果有个自定义的 JavaScript 函数,而你想在 Go 中调用它,就是看看,那个函数是在哪个对象之上,想办法获取该对象,之后就可以加以调用了,例如:
<!doctype html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8">
<title>Go wasm</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
WebAssembly API 等... 略
</script>
<script>
function hi_wasm(name) {
document.getElementById('c1').innerHTML = 'Hi, ' + name;
}
</script>
<button onClick="run();" id="runButton" disabled>Run</button>
<div id="c1">Hello, WebAssembly!</div>
</body>
</html>
hi_wasmwindow
package main
import "syscall/js"
func main() {
hi_wasm := js.Global().Get("hi_wasm")
hi_wasm.Invoke("WebAssembly")
}
c1
Invokejs.ValueInvokejs.Value