Access js localStorage stored value in VB.Net
I 开发者_StackOverflowhave a login page that stores a few values to localStorage (html5) then continues to a VB.Net page. I am looking for a method in VB that can read back those stored values and make them VB vars. Any ideas?
The VB.NET code-behind is running on the server and has no direct access to the local storage API of the browser.
You can, however, easily fill some hidden fields on the login page, using JavaScript, which will be posted on submit and can be read from the code-behind of the .NET page.
Something like this (not tested):
this.document.getElementById("HIDDEN_FIELD_ID").value = localStorage.STORED_VALUE;
...
<input type="hidden" id="HIDDEN_FIELD_ID" />
...
On the .NET page the value can be read like:
Request.Form("HIDDEN_FIELD_ID"
)
(There are other ways, but this one is easy to grasp.)
Be aware that login data in localStorage can be accessed (and modified) by the user, so make sure you are not creating a security risk.
This sample uses the above concept with VB Code:
Here is the html body element:
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="hfLoaded" runat="server" />
<asp:HiddenField ID="hfLocalStorage" runat="server" />
</form>
<script type="text/javascript">
// Load LocalStorage
localStorage.setItem('strData', 'Local storage string to put into code behind');
function sendLocalStorageDataToServer()
{
// This function puts the localStorage value in the hidden field and submits the form to the server.
document.getElementById('<%=hfLocalStorage.ClientID%>').value = localStorage.getItem('strData');
document.getElementById('<%=form1.ClientID%>').submit();
}
// This checks to see if the code behind has received the value. If not, calls the function above.
if (document.getElementById('<%=hfLoaded.ClientID%>').value != 'Loaded')
sendLocalStorageDataToServer();
</script>
Here is the page load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim s As String
s = hfLocalStorage.Value
'This next line prevents the javascript from submitting the form again.
hfLoaded.Value = "Loaded"
End Sub
Now your code behind has the localStorage value available to it.
精彩评论