用uniapp写网页,编译到h5,运行在百度app的内置浏览器,在ios手机上第一次打开,读取不到uni.setStorageSync设置的缓存数据,第二次打开页面就可以,但是在安卓端一切正常。
结合cookie一起,封装一个缓存文件 common/storage.js
// 写入 Cookie
function setCookie(key, value, days = 7) {
// 1. 模拟 uni.setStorageSync,如果是对象/数组,先转 JSON 字符串
let saveValue = value
if (typeof value === 'object') {
try {
saveValue = JSON.stringify(value)
} catch (e) {
console.error('JSON序列化失败', e)
}
}
var expires = ''
if (days) {
var date = new Date()
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
expires = '; expires=' + date.toUTCString()
}
// 使用 encodeURIComponent 防止中文或特殊字符乱码
document.cookie = key + '=' + encodeURIComponent(saveValue) + expires + '; path=/'
}
// 读取 Cookie
function getCookie(key) {
var nameEQ = key + '='
var ca = document.cookie.split(';')
for (var i = 0; i < ca.length; i++) {
var c = ca[i]
while (c.charAt(0) == ' ') c = c.substring(1, c.length)
if (c.indexOf(nameEQ) == 0) {
// 1. 获取原始字符串并解码
let val = decodeURIComponent(c.substring(nameEQ.length, c.length))
// 2. 尝试还原 JSON,模拟 uni.getStorageSync 的行为
try {
return JSON.parse(val)
} catch (e) {
// 如果不是 JSON 格式,直接返回字符串
return val
}
}
}
return '' // uni.getStorageSync 找不到时返回空字符串
}
// 统一封装:优先用 Storage,失败用 Cookie 兜底
export const myStorage = {
set: (key, value) => {
// 百度App iOS端:为了保险,同时写 Storage 和 Cookie
uni.setStorageSync(key, value)
setCookie(key, value)
},
get: (key) => {
// 1. 优先读 Storage
let res = uni.getStorageSync(key)
// 2. 如果 Storage 是空的(iOS首次加载 bug),则读 Cookie
if (res === '' || res === null || res === undefined) {
res = getCookie(key)
}
return res
}
}
使用时先引用
import { myStorage } from '@/common/storage.js';
// 存
myStorage.set('userInfo', userInfo);
// 取
const userInfo = myStorage.get('userInfo');



sea2025-01-04 10:52
发表在:《心之力》——毛泽东叩拜
g8Yww2UK2024-11-26 11:01
发表在:微信小程序下载mp4视频失败saveVideoToPhotosAlbum :fail invalid video type!已解决!看看呢
凡尘神域2024-11-04 13:35
发表在:炫酷可装杯的艺术签名商务签名设计,看这里!不错
CqbcImLl2024-11-03 22:38
发表在:微信小程序下载mp4视频失败saveVideoToPhotosAlbum :fail invalid video type!已解决!学习下
sea2024-11-02 12:42
发表在:微信小程序下载mp4视频失败saveVideoToPhotosAlbum :fail invalid video type!已解决!123123