Technologies:
Tolerim
a month ago
When switching controllers, the ability to set a cookie in _layout.cshtml is not accessible.
<button type="button" onclick="setCookie('cookiePolicy', '1')"> Accept </button>
$(window).on('load', function() {
var cookieBox = document.cookie.indexOf('cookiePolicy');
if (cookieBox == -1)
$('#cookieBox').modal('show');
}
- Write the cookie to be accessible domain-wide
- Read cookies domain-wide?
Answers(2)
Vogi
a month ago
Verified Answer
You can write the cookie to be accessible domain-wide by setting the cookie's domain attribute to the domain name of your website. For example, if your website is "example.com", you can set the domain attribute of the cookie to ".example.com" (note the leading dot). This will make the cookie accessible to all subdomains of "example.com".To read cookies domain-wide, you can use JavaScript's document.cookie property. The document.cookie property returns all cookies stored in the browser for the current domain. You can then parse this string to get the value of a specific cookie.I hope this helps! Let me know if you have any other questions.
Sources
Cookie path and its accessibility to subfolder pagesCreating a JavaScript cookie on a domain and reading it across sub ...Cookies, document.cookie - JavaScriptSharing cookies between different domains - Mediumhttpwebrequest - Domain Wide Cookies - Stack OverflowUsing HTTP cookies - HTTP | MDN - Mozilla DeveloperTolerim
a month ago
To make the cookie accessible domain-wide, you can set the cookie's path to the root directory of your domain.
Change your setCookie function to include the path:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
var path = "path=/";
document.cookie = cname + "=" + cvalue + ";" + expires + ";" + path + ";";
}
By adding path=/ to the end of the cookie string, the cookie will be accessible from the root of your domain.
Alternatively, to read cookies domain-wide, you can use document.cookie to retrieve all cookies that are accessible to the current domain. You can then check for the existence of your cookiePolicy cookie using a regular expression pattern. Here's an updated version of your $(window).on('load') function that checks for the cookie domain-wide:
$(window).on('load', function() {
var cookieBox = document.cookie.match(/(^|;)cookiePolicy=1(;|$)/);
if (!cookieBox)
$('#cookieBox').modal('show');
});
This will check if the cookiePolicy=1 substring exists within document.cookie, regardless of the cookie's path.