海涛博客

微信浏览器返回不刷新的问题(Android/iOS)

记录微信内置浏览器在 Android 与 iOS 上返回页面不刷新的问题,分析缓存与页面事件原因并给出处理方案。

评论
<script>
    //替换url中的参数值
    function changeUrlArg(url, arg, val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + val;
        return url.match(pattern) ? url.replace(eval('/(' + arg + '=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url + '&' + replaceText : url + '?' + replaceText);
    }

    $(function () {
    //适用于IOS
        if (isIOS()) {
            window.onpageshow = function (event) {
                if (event.persisted) {
                    window.location.reload()
                }
            };
        } else {
            //适用于安卓
            var page_server_time = $("input[name='page_server_time']").val();
            if (page_server_time) {
                var cookie_server_time = GetCookie('page_server_time');
                 //缓存时间大于页面服务器时间,说明页面是旧页面,强制刷新(刷新的时候,页面服务器时间会更新为最新时间,所以不会一直刷新)
                if (cookie_server_time && parseInt(cookie_server_time) >= parseInt(page_server_time)) {
                    var html = changeUrlArg(window.location.href, 'v', Math.random() * 100);
                    window.location.href = html;
                } else {
                    SetCookie('page_server_time', page_server_time);
                }
            }
        }
    });
</script>
 

评论

推荐阅读

订阅邮件

订阅更新,及时收到最新文章。

作者