如何在Javascript的popstate事件上执行location.reload时维护浏览器历史记录

如何解决如何在Javascript的popstate事件上执行location.reload时维护浏览器历史记录

因此,在一种情况下,我将使用IndexError: .iloc requires numeric indexers,got [array([False,False,...,False]) array([False,False]) ... array([False,True,False]) 8428 array([False,True])] 函数生成所有URL。我没有为此使用任何服务器端技术。我仅从服务器获取所有数据一次,然后使用history.pushState生成URL。

现在我遇到的问题是使用Javascript函数,该函数基本上模拟了浏览器的后退按钮行为。

一切正常,只需单击一次后退按钮即可。

popstate

一个后退按钮事件发生后,我无法查看该浏览器的任何以前的历史记录。我假设它是由于 $(window).on('popstate',function (event) { location.reload(true); //window.location.href = document.location; //console.log("location: " + document.location); }); 方法而发生的。我也尝试存储所有位置,然后进行重定向,但同样的事情,刷新一次后浏览器历史记录就会丢失。

有没有一种方法可以使浏览器在多次单击后退按钮时不会丢失其历史记录?

如果为此提供一个location.reload选项,那么如果有人可以分享这方面的知识,那就太好了。

解决方法

我写了一个围绕History API构建的简单插件,该插件在我的项目中使用。它将满足您的要求。

        // instantiate the QueryString Class.            
        qsObj=new QueryString({

            onPopstate: function(qsParams,data,dataAge,e) {
                // This function is called on any window.popstate event
                //   -- triggered when user click browser's back or forward button.
                //   -- triggered when JS manipulates history.back() or history.forward()
                //   -- NOT triggered when any of the QueryString methods are called (per the native behavior of the HTML5.history API which this class uses.)
                //   -- Might be triggered on page load in some browsers.  You can handle this by checking for the existence of data,eg:  if(data){ 'do something with the data' }else{ 'move along nothing to do here' }

                console.log('executing onPopstate function');
                console.log('page query string parameters are: ',qsParams);
                console.log('stored page data is: ',data);
                console.log('dataAge is:',' seconds old');

                // do stuff..

                if(data) {
                    if(dataAge && dataAge<=20) {
                        // use the stored data..

                    } else {
                        // it's old data get new..
                        
                    }
                } else {
                    // the current page has no stored data..
                }
            },onDocumentReady: function(qsParams) {
                // Document ready is only called when a page is first browsed to or the page is refreshed.
                // Navigating the history stack (clicking back/forward) does NOT refire document ready.
                // Use this function to handle any parameters given in the URL and sent as an object of key/value pairs as the first and only parameter to this function.

                console.log('executing onDocumentReady function');
                console.log('page query string parameters are:',qsParams);

                // do stuff..
            }

        });

插件使用情况:

// == QueryString class =============================================================================================
//
//    Modifies the query string portion of a browsers URL,updates the browsers history stack - saving page data 
//    along with it,all without reloading the page.
//    Can be used to simply obtain querystring parameter values as well.    
//
//    == Instantiate: ================================
//
//    var qsObj=new QueryString(
//
//        onPopstate: function(qsParams,e) {
//
//            // This function is called on any window.popstate event
//            //   -- triggered when user click browser's back or forward button.
//            //   -- triggered when JS manipulates history.back() or history.forward()
//            //   -- NOT triggered when any of the QueryString methods are called (per the native behavior of the
//            //      HTML5.history API which this class uses.)
//            //   -- Might be triggered on page load in some browsers.  You can handle this by checking for the 
//            //      existence of data,eg:  
//            //            if(data){ 'do something with the data' }else{ 'move along nothing to do here' }
//
//            // -- qsParams: is an object that contains the current pages query string paramters as key:value pairs.
//            // -- data: is an object that contains any page data that was stored at the time that this page was added
//            //    to the history stack via this class (or any HTML5 history API method),otherwise this value is NULL!
//            // -- dataAge:  null if data is null or the page data was not added via the methods in this class,//            //    otherwise the value is the age of the data in seconds.
//            // -- e: the event object if you want it.
//
//            if(data){
//                if(dataAge && dataAge <= 600){ // do it this way otherwise you'll error out if dataAge is null.
//                    // There is data and it is less than 10 minutes old.
//                    // do stuff with it..
//                }
//            }
//        },//
//        onDocumentReady: function(qsParams){
//            // Document ready is only called when a page is first browsed to or the page is refreshed.
//            // Navigating the history stack (clicking back/forward) does NOT refire document ready.
//            // Use this function to handle any parameters given in the URL and sent as an object of key/value pairs as 
//            // the first and only parameter to this function.
//
//            // do stuff with any qsParams given in the URL..
//
//        }
//
//    });
//
//
//    == The following methods are available: =======================================
//
//
//    var qsParams = qsObj.parseQueryString(); // returns an object that contains the key/value pairs of all the query 
//                                             // string parameter/values contained in the current URL,or an empty object
//                                             // if there are none.
//
//
//    qsObj.update({
//
//        // Use this method to add/remove query string parameters from the URL and at the same time update,or add to,the 
//           browser history stack with the ability to also save page data in with the history.
//
//        opType: 'auto',//        //  -- Optional. Allowed values: ['replace'|'push'|'auto'],Default is 'auto' unless 'push' or 'replace' is 
//        //     specifically given.
//        //  -- 'push':    Adds the new URL and any page data onto the browser history stack.
//        //  -- 'replace': Overwrites the current page history in the stack with the new URL and/or page data
//        //  -- 'auto':    compares the initial qs parameters with the updated qs parameters and if they are the same 
//        //      does a 'replace',if they are different does a 'push'.
//
//        qsParams: {
//            hello: 'world',//            another: 'pair'
//        },//        //  -- Optional. Object that contains key/value pairs to add to the query string portion of the URL.
//        //  -- Will entirely replace what is/isn't currently in the query string with the given key/value pairs.
//        //  -- The parameters contained in the url querystring will be made,or unmade,based on the key/value pairs 
//        //     included here so be sure to include all of the pairs that you want to show in the URL each time.
//
//
//        data: {
//           key1: 'value1',//           key2: 'value2'
//        }
//        // Optional,Object that contains key/value pairs to store as page data in the browser history stack for this page.
//
//        // ** If qsParams and data are ommitted then nothing silently happens. (This is not the same as given but empty,//        //    in which case something happens.)
//
//    });
//
//
//    qsObj.Clear({
//
//       // Use this method to remove all query string parameters from the URL and at the same time update,the
//       // browser history stack with the ability to also save page data in with the history.
//
//       optype: 'auto' // optional,defaults to auto.
//
//       data: {} // Optional,defaults to empty object {}.
//    });
//
// =========================================================================================================================

插入代码:

; (function () {
var Def = function () { return constructor.apply(this,arguments); };
var attr = Def.prototype;

//== list attributes
attr.popstateCallback = null;
attr.docreadyCallback = null;
attr.skipParseOnInit = false;
attr.currentQS;

//== Construct
function constructor(settings) {
    if (typeof settings === 'object') {
        if ('onPopstate' in settings && typeof settings.onPopstate === 'function') {
            this.popstateCallback = settings.onPopstate;
        }
        if ('onDocumentReady' in settings && typeof settings.onDocumentReady === 'function') {
            this.docreadyCallback = settings.onDocumentReady;
        }
    }
    if (this.skipParseOnInit !== true) {
        this.currentQS = this.parseQueryString();
    }
    var self = this;
    if (typeof this.popstateCallback === 'function') {
        $(window).on('popstate',function (e) {
            var data = null;
            var dataAge = null;
            if (typeof e === 'object' && 'originalEvent' in e && typeof e.originalEvent === 'object' && 'state' in e.originalEvent && e.originalEvent.state && typeof e.originalEvent.state === 'object') {

                data = e.originalEvent.state;
                if ('_qst_' in data) {
                    dataAge = ((new Date).getTime() - e.originalEvent.state['_qst_']) / 1000; // determine how old the data is,in seconds
                    delete data['_qst_'];
                }
            }
            var qsparams = self.parseQueryString();
            self.popstateCallback(qsparams,e);
        });
    }

    if (typeof this.docreadyCallback === 'function') {
        $(document).ready(function () {
            self.docreadyCallback(self.currentQS);
        });
    }
}

//== Define methods ============================================================================

attr.parseQueryString = function (url) {
    var pairs,t,i,l;
    var qs = '';
    if (url === undefined) {
        var loc = window.history.location || window.location;
        qs = loc.search.replace(/^\?/,'');
    } else {
        var p = url.split('?');
        if (p.length === 2) {
            qs = p[1];
        }
    }
    var r = {};
    if (qs === '') {
        return r;
    }
    // Split into key/value pairs
    pairs = qs.split("&");
    // Convert the array of strings into an object        
    for (i = 0,l = pairs.length; i < l; i++) {
        t = pairs[i].split('=');
        var x = decodeURI(t[1]);
        r[t[0]] = x;
    }
    return r;
};

//-- Get a querystring value from it's key name         
attr.getValueFromKey = function (key) {
    var qs = this.parseQueryString();
    if (key in qs) {
        return decodeURIComponent(qs[key].replace(/\+/g," "));
    } else {
        return null;
    }
};

//-- if urlValue is given then qsParams are ignored.    
attr.update = function (params) {
    if (typeof params !== 'object') { return; }

    var urlValue = null;
    var data = {};
    if ('data' in params) {
        data = params.data;
        urlValue = '';
    }

    var opType = 'opType' in params ? params.opType : 'auto';

    if ('urlValue' in params && typeof params.urlValue === 'string') {
        urlValue = params.urlValue;
        if (opType === 'auto') {
            var loc = window.history.location || window.location;
            if (loc.protocol + '//' + loc.host + loc.pathname + loc.search === urlValue || loc.pathname + loc.search === urlValue) {
                opType = 'replace'; // same URL,replace
            } else {
                opType = 'push'; // different URL,push
            }
        }
    } else if ('qsParams' in params && typeof params.qsParams === 'object') {

        var pairs = [];
        for (var key in params.qsParams) {
            pairs.push(key + '=' + params.qsParams[key]);
        }
        urlValue = '?' + pairs.join('&',pairs);
        if (opType === 'auto') {
            if (this.compareQsObjects(params.qsParams,this.currentQS) === false) { // different                    
                this.currentQS = params.qsParams;
                opType = 'push';
            } else { // same                    
                opType = 'replace';
            }
        }
    }
    this.replaceOrPush(urlValue,opType);
};

//== Add querystring
//-- just an alias to update
attr.add = function (params) {
    return this.update(params);
};

//== Remove specified querystring parameters
//   -- Use clear() method to remove ALL query string parameters
attr.remove = function (params) {
    var urlValue = null;
    var qsChanged = false;
    if ('qsParams' in params && params.qsParams.length > 0) {
        var qs = this.parseQueryString();
        var key;
        for (var i = 0,l = params.qsParams.length; i < l; ++i) {
            key = params.qsParams[i];
            if (key in qs) {
                delete qs[key];
                qsChanged = true;
            }
        }
    }
    if (qsChanged === true) {
        var pairs = [];
        for (key in qs) {
            pairs.push(key + '=' + qs[key]);
        }
        urlValue = '?' + pairs.join('&',pairs);
        var data = 'data' in params ? params.data : {};
        var opType = 'opType' in params ? params.opType : '';
        this.replaceOrPush(urlValue,opType);
    }
    return;
};

//== Delete querystring
//-- just an alias to remove
attr.delete = function (params) {
    return this.remove(params);
};

//== Removes all query string parameters.
//   Use remove() method to remove just the given parameters 
attr.clear = function (params) {
    params = typeof params === 'undefined' ? {} : params;
    var urlValue = window.history.location || window.location;
    urlValue = urlValue.protocol + '//' + urlValue.host + urlValue.pathname;
    var data = 'data' in params ? params.data : {};
    var opType = 'opType' in params ? params.opType : '';
    this.replaceOrPush(urlValue,opType);
    return;
};

//== Simple wrapper to the HTML5 history API's replaceState() method.
//   --also used internally
attr.replaceState = function (urlValue,data) {
    if (typeof urlValue !== 'string') {
        return;
    }
    if (typeof data !== 'object') {
        data = {};
    }
    data['_qst_'] = (new Date).getTime(); // store a timestamp value        
    history.replaceState(data,'',urlValue);
};

//== Simple wrapper to the HTML5 history API's pushState() method.
//   --also used internally
attr.pushState = function (urlValue,data) {
    if (typeof urlValue !== 'string') {
        return;
    }
    if (typeof data !== 'object') {
        data = {};
    }
    data['_qst_'] = (new Date).getTime(); // store a timestamp value        
    history.pushState(data,urlValue);
};

//-- internal use - simple gatekeeper to decide if there is anything to do and will default to 'replace' opType if this value is not given.
attr.replaceOrPush = function (urlValue,opType) {
    // is there anything to do?
    if (typeof urlValue === 'string' || typeof data === 'object') {
        // yes,what type of operation are we going to do?
        if (opType === 'push') {
            this.pushState(urlValue,data);
        } else {
            this.replaceState(urlValue,data);
        }
    }
    return;
};

// == internal use - compares the existing qs with a potentially updated one to see if they are the same (returns true) or not (returns false)
attr.compareQsObjects = function (a,b) {
    if (typeof a === 'object' && typeof b === 'object') {
        var aa = [];
        var bb = [];
        for (k in a) {
            aa.push(k + a[k]);
        }
        aa.sort();
        for (k in b) {
            bb.push(k + b[k]);
        }
        bb.sort();
        if (aa.join('') !== bb.join('')) { return false; }
        return true;
    }
    return null;
};

//unleash your class
window.QueryString = Def;

})();

,

嗯,这实际上是不可能的。 我正在考虑的唯一技巧是在触发window.location.href事件时更改popstate,并将您的历史记录作为URL参数传递。

$(window).on('popstate',function (event) {
    window.location.href = 'https://here.com?history = ' + yourHistory;
});

您需要弄清楚如何使用此方法发送历史记录,并在到达新页面时进行处理,以便用户再次单击“后退”按钮时可以再次发送历史记录。 您还必须确保生成的URL不太长。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res