0

I want to create and maintain different cookies for different tab in the same browser using asp.net with c#. I want to create cookie that will be accessible to only one tab. If another request is made with another tab then it will be consider as new request for that tab and create cookie for that new tab.

So I want unique cookie for all tabs in the same browser. How can i do this with C# code?

Smi
  • 13,850
  • 9
  • 56
  • 64
Herin
  • 704
  • 3
  • 18
  • 34

2 Answers2

1

I don't think you can tell the browser to "only read this cookie for this page in this tab", and "only read that other cookie for the same page in this other tab". You would probably have to read all the cookies for each instance of the page (i.e. for each different tab), and then use some kind of identifier in the cookies themselves to decide which to use in a particular case.

A general idea:

If you can add an easily readable "key" to a cookie, then you can loop over all of them, and only make use of the values from the cookie with a key matching a key in the page.

The key in the page could be generated by the server for each new request. You could store it in a input field of type "hidden" (or in the viewstate storage perhaps?).

Kjartan
  • 18,591
  • 15
  • 71
  • 96
1

In javascript, you can set cookies by path only if you are on that path already like so:

If you are at www.yourwebsite.com/firstTab you can set this cookie:

document.cookie = "myField=blah;expires=10/10/2020;path=/firstTab";

And if you are at www.yourwebsite.com/secondTab you can set this cookie:

document.cookie = "myField=blah2;expires=10/10/2020;path=/secondTab";

If you go to /firstTab and do document.cookie, you will only see myField=blah and if you do the same in /secondTab you will only see myField=blah2. Here's the W3Schools tutorial for javascript cookies.

If you want to include information that's passed from C#, simply add it into a hidden field and get it from there using javascript.

Caveat

If your tabs take you to different paths then this works. But if you only use hashes then it won't work because the hash is not part of the path. You can see this with document.location. You'll have to share cookies across tabs and parse the values yourself.