在微信网页开发中,经常会用到返回按钮
有时候需要在用户点击返回的时候跳转到指定页面,并且再次返回到另一个指定页面,不再返回当前页。
例如有A,B,C三个网页,其中B为第三方网页,比如百度,需求如下:
首页是A,从A进来点击返回按钮后需跳转到B,
再次点击返回需要跳转到C,C页面返回后又进入B,
依次在B,C间循环。不再出现A页面。
具体代码:
A:
-
使用原生的popstate方法
(function () { if (!window.history.pushState || !document.dispatchEvent) return; var href = location.href; var flag = true; var voidFn = function () { }; var fn = voidFn; var dispatchFn = function () { var evt = document.createEvent('Event'); evt.initEvent('popstate', true, true); window.dispatchEvent(evt); }; window.addEventListener('load', function () { history.replaceState({}, '', '/C.php');//不能跨域,可在本地脚本中进行跳转 history.pushState({}, '', href); window.addEventListener('popstate', function () { dispatchFn = voidFn; if (!flag) { $.get("/xx/hit", { origin: xxx, type:xxx, param: xxx }, function () { location.href = "https://blog.csdn.net/weixin_43627766/article/details/88852079";//B网站 }); } flag = false; }, false); setTimeout(function () { fn = dispatchFn; fn(); }, 20); }, false);
})();
-
使用jquery.history.js库(需要引入jquery.history.js文件)
$(function(){ var hashurl = C if (!window.history.pushState || !document.dispatchEvent) exit(); var href = location.href; var enable = true; var replace = "/jumpC.php?url=" + hashurl;//跳转到C的本地脚本 var redirect = "https://blog.csdn.net/weixin_43627766/article/details/88852079";//B网站 history.replaceState({}, '', replace); history.pushState({}, '', href); History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate //popstate有一定的兼容性限制 if (!enable) { location.href = redirect; } enable = false; }); });
C页面:
(function () {
if (!window.history.pushState || !document.dispatchEvent) return;
var href = location.href;
var flag = true;
var voidFn = function () {
};
var fn = voidFn;
var dispatchFn = function () {
var evt = document.createEvent('Event');
evt.initEvent('popstate', true, true);
window.dispatchEvent(evt);
};
window.addEventListener('load', function () {
history.pushState({}, '', href);
window.addEventListener('popstate', function () {
dispatchFn = voidFn;
if (!flag) {
location.href = B
}
flag = false;
}, false);
setTimeout(function () {
fn = dispatchFn;
fn();
}, 20);
}, false);
})();
总结
返回页主要注意pushState和replaceState的灵活使用
前者是网历史记录后面添加,后者是清空记录并替换。