鸿蒙学习 - web 原生和js相互调用
import webview from '@ohos.web.webview'
@Entry
@Component
struct Index {
webController: WebviewController = new webview.WebviewController
build() {
Column(){
Web({
src:"https://m.baidu.com",
controller:this.webController
})
.width('100%').height('80%')
Button("调用js方法").onClick(() => {
// 原生代码调用js方法的写法:
this.webController.runJavaScript("testJsAction()", (error, res) => {
console.log("错误信息:"+`${error}`+"js返回的结果:"+`${res}`)
})
})
Button("注入js方法").onClick(() => {
// 给js注入方法,让h5的同学调用的写法:
// h5的同学就可以调用方法getUserAction,获取用户对象的json了
this.webController.registerJavaScriptProxy({
getUserAction:() => JSON.stringify({"userName":"xiaoming"})
},"windowArtTS",["getUserAction"])
})
}.width('100%').height('100%')
}
}
/*
需要在module.json5的文件中添加:
*
* "pages": "$profile:main_pages", // 在这行并列的位置添加下面代码。
"requestPermissions": [
{
"name": 'ohos.permission.INTERNET'
}
],
*/