解决微信浏览器无法使用reload()刷新页面

发布时间:2019-03-01 15:27:52编辑:丝画阁阅读(1219)


以下的方式都没有解决微信浏览器网页刷新问题!


场景是这样子的,页面在初始化时有一个ajax请求,在页面上有一个按钮,点击的时候执行window.location.reload(),正常情况reload()后页面依然会向后台发出请求,但在安卓的微信浏览器中reoad后请求的一直是第一次打开页面时请求的数据。可以理解为请求被缓存了,但没有实测,也不知道是否是缓存。

解决方法是,使用window.location.href="window.location.href+随机数" 代替 window.location.reload()。切记,一定要加随机数,否则一样不会起作用。当然也可以用一个a标签,然后设置href="window.location.href + 随机数"。

再进一步的话可以只针对微信浏览器作此设置,那么就得判断是否微信浏览器。可以通过window.navigator.userAgent进行判断,结果是,Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13F69 MicroMessenger/6.3.16。根据关键字 MicroMessenger 来判断是否是微信内置的浏览器。判断函数如下

复制代码
function isWeiXin(){ var ua = window.navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i) == 'micromessenger'){ return true;
    }else{ return false;
    }
}

javascript 微信浏览器上不能实现刷新解决方案

        window.location.href='/home/gheliceshi/?v='+10000*Math.random();
  后缀加个版本号就可以啦


在链接后加上随机数即可解决:

function refresh() {
    var random = Math.floor((Math.random() * 10000) + 1);
    var url = decodeURI(window.location.href);
    if (url.indexOf('?') < 0) {
        url = url + "?random" + random;
    } else {
        url = url.substr(0, url.indexOf('?random')) + "?random" + random;
    }
    window.location.href = url;
}

解决办法;

就是使用location.href代替reload(),建议大家使用location.href来进行刷新或者跳转

方法一;

window.location.href=window.location.href+"?id="+10000*Math.random();

方法二;

window.location.href = location.href+'?time='+((new Date()).getTime());




 <script type="text/javascript">

        //History 对象包含用户(在浏览器窗口中)访问过的 URL。
        var historyObj = window.history;

        //historyObj.length 返回浏览器历史列表中的 URL 数量。
        //根据historyObj.length 的数量判断是否是第一次进入此页面
        if (historyObj.length == 1) {
            localStorage.test = 1;
            $('.value').text(localStorage.test)
        } else {
            $('.value').text(localStorage.test)
        }

        $('.add').click(function(){
            localStorage.test++;
            $('.value').text(localStorage.test);
        })

        $('.remove').click(function(){
            localStorage.test--;
            $('.value').text(localStorage.test);
        })

        /*
         *  点击某个离开页面的链接
         *  在地址栏中键入了新的 URL
         *  使用前进或后退按钮
         *  关闭浏览器
         *  重新加载页面
         *  满足以上条件都触发此事件
         */
        $(window).unload(function(){
            if (historyObj.length == 1) {
                localStorage.test = 1;
            }
        })
    </script>

关键字