简体   繁体   English

Javascript或jquery事件,用于检测浏览器的“后退”按钮

[英]Javascript or jquery Event For detecting Back button of the browser

I had some research regarding how to subscribe in the event when back button of the browser is clicked but unfortunately I wasn't able to find the right answer for my problem 我进行了一些有关如何在单击浏览器的后退按钮时进行订阅的研究,但是不幸的是,我找不到适合我问题的正确答案

I tried doing this: 我尝试这样做:

var $window = $(window);

    $window.on('beforeunload', function()
    {
        commitFieldChanges();
    }); 

i used require JS for this 我为此需要JS

and the other solution for this is 另一个解决方案是

$(window).bind('beforeunload', function(){ 
    return '';
});

However all of this is not working because my application is a single page app. 但是,所有这些都不起作用,因为我的应用程序是单页应用程序。 So the page is not really loading when back button is clicked because we use # to navigate in the application in the URL so what do you think guys? 因此,当单击“后退”按钮时,页面实际上并未加载,因为我们使用在URL中的应用程序中进行导航,所以您认为呢? Any suggestion for my problem? 对我的问题有什么建议吗?

This is a way that I currently use for my app, to detect back button on some page which aimed to support modern cross-browsers both desktop and mobile. 这是我目前用于我的应用程序的一种方法,用于检测某个页面上的后退按钮,该按钮旨在支持台式机和移动设备的现代跨浏览器。

Homepage 主页

var isFromView = false;
$(function() {
  // Check if browser supports LocalStorage
  if(typeof(Storage) !== 'undefined') {
    var currentValue = localStorage.getItem('fromSource');
    if (currentValue && currentValue === 'view') {
       // Set isFromDetail to true
       isFromView = true;
    }
    else {
       localStorage.removeItem('fromSource');
    }

    try {
       // Set fromSource in localStorage.
       localStorage.setItem('fromSource', 'home');
    }
    catch (err) {
       // Need this for safari mobile private mode !!
    }
  }
});

Viewpage 浏览页面

$(function() {
  // Check if browser supports LocalStorage
  if(typeof(Storage) !== 'undefined') {
    try {
       // Set fromSource in localStorage.
       localStorage.setItem('fromSource', 'view');
    }
    catch (err) {
       // Need this for safari mobile private mode !!
    }
  }
});

++: I've gone through with history API to perform action on back button. ++:我已经使用了历史记录API来对后退按钮执行操作。 But with no success in supporting some mobile devices browsers. 但是在支持某些移动设备浏览器方面没有成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM