您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
当前回答
以下是我的看法。假设是,当URL更改但检测到文档内没有单击时,它是浏览器返回(是的,或向前)。用户点击2秒后重置,使其在通过Ajax加载内容的页面上工作:
(function(window, $) {
var anyClick, consoleLog, debug, delay;
delay = function(sec, func) {
return setTimeout(func, sec * 1000);
};
debug = true;
anyClick = false;
consoleLog = function(type, message) {
if (debug) {
return console[type](message);
}
};
$(window.document).click(function() {
anyClick = true;
consoleLog("info", "clicked");
return delay(2, function() {
consoleLog("info", "reset click state");
return anyClick = false;
});
});
return window.addEventListener("popstate", function(e) {
if (anyClick !== true) {
consoleLog("info", "Back clicked");
return window.dataLayer.push({
event: 'analyticsEvent',
eventCategory: 'test',
eventAction: 'test'
});
}
});
})(window, jQuery);
其他回答
浏览器: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>
我通过跟踪触发hashchange的原始事件(无论是滑动、单击还是滚动)来解决这个问题,这样事件就不会被误认为是简单的页面登陆,并在每个事件绑定中使用一个额外的标志。当点击后退按钮时,浏览器不会再次将标志设置为false:
var evt = null,
canGoBackToThePast = true;
$('#next-slide').on('click touch', function(e) {
evt = e;
canGobackToThePast = false;
// your logic (remember to set the 'canGoBackToThePast' flag back to 'true' at the end of it)
}
看到这个:
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
它工作得很好……
正确答案已经在那里了。我想提一下新的JavaScript API PerformanceNavigationTiming,它取代了过时的performance。navigation。
下面的代码将登录控制台“back_forward”如果用户登陆到您的页面使用后退或前进按钮。在项目中使用兼容性表之前,请先查看兼容性表。
var perfEntries = performance.getEntriesByType("navigation");
for (var i = 0; i < perfEntries.length; i++) {
console.log(perfEntries[i].type);
}
我尝试了上面的方法,但是没有一个对我有效。这是解决方案
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked...");
}
else
{
alert("Browser refresh button is clicked...");
}
}
详情请参考http://www.codeproject.com/Articles/696526/Solution-to-Browser-Back-Button-Click-Event-Handli