iOS微信浏览器和微信小程序的H5,localstorage会共存
发布于 4 年前 作者 ufan 3265 次浏览 来自 官方Issues
<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script src="https://cdn.staticfile.org/eruda/2.4.1/eruda.min.js"></script>
        <script>
            eruda.init();
        </script>
        <script>
            function getDeviceType() {
                const userAgent = navigator.userAgent;
                let deviceType = 0;
                if (userAgent.toLowerCase().indexOf("micromessenger") !== -1) {
                    if (userAgent.toLowerCase().indexOf("miniprogram") !== -1) {
                        deviceType = 5;
                    } else {
                        deviceType = 3;
                    }
                } else {
                    deviceType = 4;
                }
                return deviceType;
            }
            let deviceType = getDeviceType();
            console.log("🚀 ~ file: 测试缓存.html ~ line 51 ~ deviceType", deviceType);
            if (deviceType == 3) {
                localStorage.setItem("weixinh5", true);
            }
            if (deviceType == 5) {
                localStorage.setItem("mini", true);
            }
            if (deviceType == 4) {
                localStorage.setItem("h5", true);
            }
        </script>
    </body>
</html>

以上代码,本地起服务器,

先在微信浏览器(第二张图)中打开,再配置在小程序(第一张图)中打开,保证两次打开不跨域

微信浏览器保存的localStorage会被带到小程序环境中

仅iOS会出现

回到顶部