声明JSBridge:
/// JS 交互
private jsBridge: ThirdJSBridge = new ThirdJSBridge({
pageParams: RouterParams.getObject<ThirdPageParam>('params'),
storage: storage,
navStack: this.pageInfos,
})
//ThirdJSBridge继承BasicJSBridge
export default class ThirdJSBridge extends BasicJSBridge
//BasicJSBridge的代码为:
export default abstract class BasicJSBridge implements HarmonyCallJS {
controller: webview.WebviewController;
constructor() {
this.controller = new webview.WebviewController();
}
/**
* H5 调用原生方法处理
*/
get javaScriptProxy(): JavaScriptItem {
let result: JavaScriptItem = {
name: "HarmonyOS",
object: this.getJSCallHarmonyBridge(),
methodList: this.getBridgeMethodList(),
controller: this.controller
}
return result;
}
}
Web({
src: this.url,
controller: this.jsBridge.controller
})
.darkMode(WebDarkMode.Off)
.javaScriptAccess(true)
.javaScriptProxy(this.jsBridge.javaScriptProxy)
.zoomAccess(false)
.multiWindowAccess(false)
.cacheMode(CacheMode.Online)
.mixedMode(MixedMode.All)
.domStorageAccess(true)
.onControllerAttached(() => {
this.third.addUserAgent()
})
.onShowFileSelector((event) => {
return this.third.chooseImage(event as FileSelectorEvent)
})
.databaseAccess(true)
.fileAccess(true)
.imageAccess(true)
.textZoomRatio(100)
.password(false)
.width('100%')
.flexShrink(1)
}
.width('100%').height('100%')
二、BasicJSBridge的原生调用H5实现方法:
harmonyCallJS(name: string, ...params: Object[]) {
// 拼接参数,如 1,abc,ddd
// 并通过 funcname(1,abc,ddd) 的形式调用 H5 的方法
let args: string
if (params.length == 0) {
args = ''
} else {
args = `'${params.join("','")}'`
}
this.controller.runJavaScript(`${name}(${args})`)
}
情况:确认name和args有值且为正常,但是闪退,查看听云日志,闪退信息是:Error: Init error. The WebviewController must be assosiated with a Web component。请问,controller已经在BasicJSBridge初始化,Web初始化时通过.javaScriptProxy(this.jsBridge.javaScriptProxy) 已经吧Web和Controller绑定,为什么还未出现这个错误呢?
可以在onControllerAttached回调中使用runJavaScript方法,这个回调是Controller成功绑定到Web组件时触发的。
API文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-web-V5\#oncontrollerattached10