HarmonyOS 鸿蒙Next中注入cookie失败
HarmonyOS 鸿蒙Next中注入cookie失败
【问题描述】:鸿蒙 Web 组件 如何兼容 金山文档 webOfficeSdk Android 都是可以的,鸿蒙 Web直接加载不出来-华为开发者问答 | 华为开发者联盟
经上述问题,当时文档链接在鸿蒙web上加载不出来,是因为网址中,部分请求的header中需要使用到三方cookie中获取的值,因此需要设置putAcceptThirdPartyCookieEnabled属性允许接收第三方cookie的权限,目前可以正常显示了,但是还有存在一个问题,注入cookie不行
【问题现象】:设置putAcceptThirdPartyCookieEnabled属性允许接收第三方cookie的权限,目前可以正常显示了,但是还有存在一个问题,注入cookie不行
【版本信息】:未涉及
【复现代码】:未涉及
【尝试解决方案】:未涉及
更多关于HarmonyOS 鸿蒙Next中注入cookie失败的实战教程也可以访问 https://www.itying.com/category-93-b0.html
尊敬的开发者,您好,
对于将H5网页预置在应用本地resfile目录时,访问网页时,url为file://***,服务端请求为http|https请求,并且需要将Cookie设置在服务端请求域名下,此时就涉及第三方域名Cookie管控。
【解决方案】
Web组件设置putAcceptThirdPartyCookieEnabled为true,设置WebCookieManager实例允许发送和接收第三方Cookie。 示例代码:
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Page2 {
controller: webview.WebviewController = new webview.WebviewController();
uiContext: UIContext = this.getUIContext();
aboutToAppear(): void {
// 设置WebCookieManager实例拥有发送和接收第三方cookie的权限
webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(true);
}
build() {
Stack() {
Column() {
Web({ src: '', controller: this.controller })
.fileAccess(false)
.geolocationAccess(false)
.onControllerAttached(() => {
try {
// 设置允许可以跨域访问的路径列表
this.controller.setPathAllowingUniversalAccess([
this.uiContext.getHostContext()!.resourceDir
]);
// 访问本地资源页面
this.controller.loadUrl('file://' + this.uiContext.getHostContext()!.resourceDir + '/index.html');
} catch (error) {
console.error(
`loadUrl errorCode: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`);
}
try {
// 为服务端请求设置Cookie,使用时请替换为真实地址
webview.WebCookieManager.configCookieSync('www.example.com',
'cookie_key=cookie_value;Domain=.example.com;SameSite=None;Secure=true;HttpOnly');
} catch (error) {
console.error(`excute configCookieSync failed. error is ${error}`);
}
});
};
};
}
}
同时需要注意设置Cookie的格式:
Cookie_Key=Cookie_Value;属性;属性;...。Cookie_Key表示Cookie唯一标识,Cookie_Value表示Cookie的值,属性表示Cookie的各种属性设置,如Domain、Path、Expires等,中间使用英文分号分隔。
示例:token=123;Path=/;Domain=.example.com。
设置第三方共享Cookie,还需设置Cookie属性为:SameSite=None;Secure=true;HttpOnly。可参考上述示例代码。
更多关于HarmonyOS 鸿蒙Next中注入cookie失败的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
configCookie 参数传错或时机不对
在 aboutToAppear() 生命周期中完成 Cookie 的设置
https://bbs.itying.com/topic/693cab194ba34900416f31f0#693cab68a899160047f6229a
有host应该可以注入啊
鸿蒙Next中注入cookie失败通常因WebView未正确配置或Cookie管理接口使用不当导致。需使用ohos.web.webview.WebCookieManager的setCookie方法,并确保URL与cookie的domain/path匹配。检查是否在onLoad前调用,以及是否设置了SecurityConfig允许存储。若使用HTTP请求,需确认服务器返回Set-Cookie头处理正确。


