您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
当前回答
这将肯定工作(用于检测返回按钮点击)
$(window).on('popstate', function(event) {
alert("pop");
});
其他回答
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
alert('hello world');
}
这是唯一一个解决方案,为我工作(这不是一个一页网站)。 它支持Chrome、Firefox和Safari浏览器。
浏览器:https://jsfiddle.net/Limitlessisa/axt1Lqoz/
移动控制:https://jsfiddle.net/Limitlessisa/axt1Lqoz/show/
$(document).ready(function() { $('body').on('click touch', '#share', function(e) { $('.share').fadeIn(); }); }); // geri butonunu yakalama window.onhashchange = function(e) { var oldURL = e.oldURL.split('#')[1]; var newURL = e.newURL.split('#')[1]; if (oldURL == 'share') { $('.share').fadeOut(); e.preventDefault(); return false; } //console.log('old:'+oldURL+' new:'+newURL); } .share{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.8); color:white; padding:20px; <!DOCTYPE html> <html> <head> <title>Back Button Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body style="text-align:center; padding:0;"> <a href="#share" id="share">Share</a> <div class="share" style=""> <h1>Test Page</h1> <p> Back button press please for control.</p> </div> </body> </html>
Kotlin/JS (React)的解决方案:
import org.w3c.dom.events.Event
import kotlin.browser.document
import kotlin.browser.window
...
override fun componentDidMount() {
window.history.pushState(null, document.title, window.location.href)
window.addEventListener("popstate", actionHandler)
}
...
val actionHandler: (Event?) -> Unit = {
window.history.pushState(
null,
document.title,
window.location.href
)
// add your actions here
}
正在寻找这个问题的解决方案,并根据这里的一些答案和History.pushState()和WindowEventHandlers.onpopstate的MDN Web文档页面,将一个简单的骨架测试html放在一起。
下面的HTML和JavaScript很容易复制、粘贴和测试。
使用后退和前进浏览器按钮,快捷键,添加对URL的更改(这在某些情况下很重要)。
简单到可以向现有代码中添加关键点,并且应该是可扩展的。
<html>
<body>
<div id="p1">Option 1</div>
<div id="p2">Option 2</div>
<div id="p3">Option 3</div>
<div id="p4">Option 4</div>
<div id="c"></div>
<script>
var chg={
set:function(str){
var d=document.getElementById("c");
d.textContent=str;
},
go:function(e){
var s={"p":this.id};
chg.set(s.p);
hstry.add(s);
}
};
var hstry={
add:function(s){
var u=new URL(window.location);
u.searchParams.set("x",s.p);
window.history.pushState(s,"",u);
},
adjust:function(state){
if(state.p){
chg.set(state.p);
}
}
};
window.onpopstate=function(e){
console.log("popstate, e.state:["+ JSON.stringify(e.state) +"]");
hstry.adjust(e.state);
}
window.onload=function(){
var i,d,a=["p1","p2","p3","p4"];
for(i=0;i<a.length;i++){
d=document.getElementById(a[i]);
d.addEventListener("click",chg.go,false);
}
}
</script>
</body>
</html>
在javascript中,导航类型2意味着浏览器的后退或前进按钮被点击,浏览器实际上是从缓存中获取内容。
if(performance.navigation.type == 2)
{
//Do your code here
}