使用还是比较简单的,直接贴代码了
别忘了配置网络权限
@Entry
@Component
struct WebPage {
@State isAttachController: boolean = false
@State url: string = ''
@State title: string = ''
@Prop controller: web_webview.WebviewController = new web_webview.WebviewController()
// 与前端交互 对象
jsObj = new JsObj({
setHeaderContentCallback: (str: string) => {
this.title = str
}
});
// js 调用App方法: 需要在数组中声明,设置给 methodList:
jsArray: string[] = ["setHeaderContent", "toLogin", "jumpToBossDetailNew", "jumpToBossDetail", "jumpToCompanyDetail", "openRenewDefaultNavPageLoad", "openRenewPageLoad", "openNewPageLoad", "openBrowser"];
aboutToAppear(): void {
this.url = (router.getParams() as RouterParams).url
if (this.url.indexOf('?') > 0) {
this.url = this.url + BranchUtils.appendBranchParams()
} else {
this.url = this.url + `?${BranchUtils.appendBranchParams()}`
}
web_webview.WebviewController.setWebDebuggingAccess(true);
PreferencesUtil.getString("urlCookie").then((value) => {
// 如果连接本地调试 一定要写完整的域名 带上http
//web_webview.WebCookieManager.configCookieSync('http://10.1.65.120:5173/', value)
// 设置cookie
web_webview.WebCookieManager.configCookieSync('.sscha.com', value)
})
web_webview.once("webInited", () => {
})
eventBus.on(EventBusId.ID_LOGIN, () => {
// todo
})
}
build() {
Column() {
PubTitle({ title: this.title, isShowRightBtn: false })
Web({ src: this.url, controller: this.controller })
.width('100%')
.height('100%')
.mixedMode(MixedMode.All)
.javaScriptAccess(true)
.javaScriptProxy({
object: this.jsObj,
name: "android",
methodList: this.jsArray,
controller: this.controller,
})
.onControllerAttached(() => {
// 官方建议是在这里设置 serAgent
this.controller.setCustomUserAgent(this.controller.getUserAgent() + BranchUtils.appendBranch())
})
.onPageEnd((urlEnd) => {
console.log("onPageEnd= " + JSON.stringify(urlEnd))
})
}
.width('100%')
}
}
export interface JSCallback {
reqResult?: (code: string) => void;
setHeaderContentCallback?: (msg: string) => void;
}
export class JsObj {
callback?: JSCallback
registCallBack(callback: JSCallback) {
this.callback = callback
}
constructor(callback?: JSCallback) {
this.callback = callback
}
// ...省略代码
}
现象:
Android 、Ios 都有线上App 网页都是调试好的
鸿蒙加载有些网页加载不出来(绝大多数都加载不出来),有些能加载出来 。个人认为肯定不是ArkWeb的问题,这一块就需要跟前端调试,最后排查出的问题还真是前端的问题
排查结果
前端使用:localStorage,调用时localStorage为null,导致整个界面都加载不出来
经过前端修改,对localStorage是否为null进行判断,网页都可以正常加载出来了
官网上有一个写法,不过没验证