xxx.xxx.html:21 Uncaught TypeError: Cannot read properties of undefined (reading 'toMenu')
at goJump (xxx.xxx.html:21:32)
at HTMLButtonElement.onclick (xxx.xxx.html:1140:28)
goBack @ xxx.xxx.html:21
onclick @ xxx.xxx.html:1140 通过javaScriptProxy建立应用侧与Web侧的交互通道,将正确的点击跳转方法注册到Web页面中。
WebTest.ets示例代码如下:
import { Router } from '@kit.ArkUI';
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
class TestClass {
private routerInstance: Router | undefined = undefined;
constructor(context: UIContext) {
this.routerInstance = context.getRouter();
}
goJump() {
this.routerInstance?.pushUrl({
url: 'pages/Index',
}).catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
});
}
}
@Entry
@Component
struct WebTest {
webviewController: webview.WebviewController = new webview.WebviewController();
// 声明需要注册的对象
@State testObj: TestClass = new TestClass(this.getUIContext());
build() {
Column() {
// Web组件加载本地routerPage.html页面
Web({ src: $rawfile('routerPage.html'), controller: this.webviewController })
// 将对象注入到Web端
.javaScriptProxy({
object: this.testObj,
name: 'testObjName',
methodList: ['goJump'],
controller: this.webviewController,
})
.fileAccess(false)
.geolocationAccess(false);
};
}
} Index.ets示例代码如下:
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
} routerPage.html示例代码如下:
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,viewport-fit=cover"/>
<body>
<p>
这是一个网页
</p>
<button onclick="handleClick()">跳转其他页面</button>
</body>
</html>
<script>
function handleClick() {
// 调用ArkTS注册的方法
if (window.testObjName && typeof window.testObjName.goJump === 'function') {
window.testObjName.goJump();
} else {
console.error('未找到跳转方法');
}
}
</script>