您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
当前回答
正确答案已经在那里了。我想提一下新的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);
}
其他回答
我通过跟踪触发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)
}
我尝试了上面的方法,但是没有一个对我有效。这是解决方案
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
以下是我的看法。假设是,当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);
我的版本:
const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )
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
}