针对页面历史栈相关的事件,需要进行一个深入的学习,针对一个具体的业务场景,记录下对应的解决方案:
场景记录:
有三个页面 ABC,其中AB两个页面之间的数据可以同步,通过点击A页面的一个按钮,进入到B页面,点击客户端或者手机物理返回键的时候,可以从B页面返回A页面,点击A和B页面的一个按钮,进入到C页面,无论是从A页面进入C页面,还是从B页面进入到C页面,从C页面返回的时候,需要返回到A的上一级页面。(这里A的上一级页面进入到A的时候,是调用客户端的)
经过实践,一个比较简单的实现方式是:
A和B页面的逻辑,写入到一个html里面,页面的切换和数据同步通过观察者模式和component组件的显示和隐藏实现。在从A页面进入到B页面的过程中,调用
history.pushState(null, null, url)
,同时监听页面的 popstate 事件,在window.addEventListener('popstate', () =>{})
的回调里进行页面的显示和隐藏。C页面最终要回到A的上级页面,如果是在B页面提交,需要在提交成功的情况下,调用history.back()
方法回到A页面,然后使用location.replace(url)
方法进入到C页面,这个时候从C页面点击再返回,可以直接将当前的webview销毁,回退到A的上一级页面。
针对 history历史事件的重写,部分域名的页面切换监听不到相关的历史事件, 重写 history 等事件监听页面切换。
var _history = function(type) {
var origin = history[type]
return function() {
var rv = origin.apply(this, arguments)
var e = new Event(type)
e.arguments = arguments
window.dispatchEvent(e)
return rv
}
}
history.pushState = _history('pushState')
history.replaceState = _history('replaceState')
history.popState = _history('popState')
window.addEventListener('replaceState', function (e) {
EventEmit.instance.emit( params.host + '-history-replacestate')
})
window.addEventListener('pushState', function (e) {
EventEmit.instance.emit( params.host + '-history-pushstate')
})
window.addEventListener('popstate', function(e) {
EventEmit.instance.emit( params.host + '-history-popstate')
})
网友评论