简体   繁体   English

使用JavaScript在刷新时将查询字符串附加到url

[英]Appending a query string to the url on refresh using javascript

I am trying to read a label and append its value as a query string once the user hits the refresh button on their browser. 我试图读取标签,并在用户点击浏览器上的刷新按钮后将其值附加为查询字符串。 The code I have so far is: 到目前为止,我的代码是:

 function AppendQueryString() {
            var currUrl = document.location;
            var trackingNbr = $("#lblTrackingNbr").text();
           if (window.location.href.indexOf("?TrackingNumber=") <= 0 && trackingNbr !== null) {
                document.location = currUrl + "?TrackingNumber="+ trackingNbr;  
            }
        }

        window.onbeforeunload = AppendQueryString(); 

The problem is, the trackingNbr variable is always null even though the label has the value before I hit refresh. 问题是,即使标签具有在刷新前的值,该trackingNbr变量也始终为空。 What am I doing wrong or is there a better way of doing this ? 我做错了什么,还是有更好的方法呢?

SessionStorage would be a good solution, with something like this: SessionStorage将是一个很好的解决方案,例如:

sessionStorage.setItem("trackingNbr", trackingNbr);

When the refresh button is clicked, you can pull this value back from session storage easily: 单击刷新按钮后,您可以轻松地从会话存储中拉回该值:

var trackingNbr = sessionStorage.getItem("trackingNbr");

Security: Because this is session storage rather than local storage, the value will be cleared from the browser when the session ends. 安全性:因为这是会话存储而不是本地存储,所以会话结束时将从浏览器中清除该值。 Note that only your domain can access whatever you put into either session or local storage. 请注意,只有您的域可以访问您放入会话或本地存储中的任何内容。 However, a knowledgeable end user can read the value by using developer tools in any of the major browsers. 但是,有知识的最终用户可以通过使用任何主要浏览器中的开发人员工具来读取值。

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

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