加入下方官方优快云班级,得鸿蒙礼盒
本期活动时间:2025年8月1日-12月31日
问题现象
APP中使用Web组件加载在线网页,网页内部会跳转到新网页,JS交互无法响应,方法不执行。
问题代码示例参考如下:
onControllerAttached(() => {
webViewControllerManager.addWebviewController(this.webViewController)
if (this.registerJSProxyArray && this.registerJSProxyArray.length > 0) {
this.registerJSProxyArray.forEach((each: RegisterJSProxyType) => {
this.webViewController.registerJavaScriptProxy(each.obj, each.name,
getMethodListByClass(each.obj))
})
}
this.webViewController.refresh()
this.handleControllerAttached?.()
let agent = this.webViewController?.getUserAgent()
agent = "ThemeableBrowser/1.0 " + agent + "changan-incall"
this.webViewController?.setCustomUserAgent(agent)
if (this.resUrl) {
try {
this.webViewController.setPathAllowingUniversalAccess([
getContext().resourceDir,
getContext().filesDir + "/cacheResources"
])
let url = "file://" + getContext().resourceDir + '/' + this.resUrl
if (this.resUrl.includes('caccmcs.changan.com.cn/prod/dist')) {
url = this.resUrl
}
Logger.warn(TAG, `onControllerAttached resourceDir:${getContext().resourceDir}
filesDir:${getContext().filesDir} url:${url}`)
this.webViewController.loadUrl(url)
} catch (error) {
Logger.error(TAG, `ErrorCode: ${(error as BusinessError).code}, Message: ${(error as
BusinessError).message}`);
}
}
})
背景知识
- 前端页面调用应用侧函数:开发者使用Web组件将应用侧代码注册到前端页面中,注册完成之后,前端页面中使用注册的对象名称就可以调用应用侧的方法,实现在前端页面中调用应用侧方法。
- onLoadIntercept:当Web组件加载url之前触发该回调,用于判断是否阻止此次访问。
- OnLoadInterceptEvent:定义截获资源加载时触发的回调。其属性data(类型为WebResourceRequest)包含url请求的相关信息Web组件获取资源请求对象。
问题定位
页面初始化的情况下加载网页A,然后发现网页内部跳转加载了目标链接,bondApp插件对象丢失了。尝试页面直接加载目标链接,不会出现插件对象丢失情况。当监听到url和之前的url域名不一致,尝试重新注册一遍JS,问题可以解决。
分析结论
当网页发生整页跳转(非单页应用的路由切换)加载新页面时,原页面上下文会被完全重置。因此,之前注册到window上的自定义JS对象会丢失。
修改建议
需要监听页面url是否发生变化,如果发生变化就重新注入对象。

被折叠的 条评论
为什么被折叠?



