Create a cookie using the JavaScript option

Can you specify cookie settings in JavaScript like CookieOptions in C#?

var options = new CookieOptions
{
    IsEssential = true
};

I am aware that you can set a cookie in JavaScript using document.cookie = cookieString, but is there a way to include options?

Answer №1

Overview

I am not aware of any JavaScript methods that mimic C#'s options functionality.

Two JavaScript functions I have previously written are setCookie and getCookieValue for setting cookies.

var common = common || {}
common.cookieManager = common.cookieManager || {};
common.cookieManager.getCookieValue = (name) => (
  document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)

/**
 * set cookie with name value and life time
 * @param {string} name cookie name
 * @param {string} value cookie value
 * @param {number} expireTime s
 */
common.cookieManager.setCookie = async (name, value, expireTime = 0) => {
  const expires = (new Date(Date.now() + expireTime * 1000)).toUTCString();
  document.cookie = `${name}=${value}; expires=` + expires + ";path=/;"
}

You can customize the setCookie function by adding parameters based on Document.cookie


However, if you are using the .NET MVC framework, it may be more advantageous to set cookies in the backend.

In your .NET WebApi Controller, you should utilize the Response property.

Utilize Controller.Response to set cookies using the CookieOptions class

Example code:

Response.Cookies.Append("key", "value", new CookieOptions() { Expires = DateTime.Now.AddMinutes(30), IsEssential = true });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to send URL variables to express.js similar to how it's done in PHP?

Currently in the process of converting my PHP website to Express.js. There are numerous scripts on my frontend that generate links in the format page.php?id=10&something=anything. Is there a way in Express.js to capture variables from URLs structured ...

Leverage data retrieved from a JSON response to dynamically populate variables on a webpage through an AJAX API

After making an AJAX call to my API and receiving JSON data, I am looking to dynamically update my webpage using specific values from the JSON response. <div class="Name"></div> <div class="Role"></div> <div class="Location"> ...

Tips for organizing an AngularJS bootstrap Modal for a search feature

I need help with integrating AngularJs, bootstrap, and an API to populate a bootstrap modal popover with JSON data upon clicking a search function button. While I have successfully implemented the data flow, I am struggling to trigger the modal using the b ...

Customized webpage content using AJAX for interactive map selections

I have integrated JQVMaps into a WordPress website to display a dynamic world map. The goal is to update the content of the page based on the region that the user clicks. Below is a snippet of the code I have implemented as a proof of concept: <div ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Easy method for importing videos into NextJs

Import Coding Guidelines Encountering an error after importing the code, unable to find any solutions online ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

React - Stopping the Submit Action

Recently, I have been delving into React development. In my exploration, I have incorporated the Reactstrap framework into my project. However, I have encountered an issue where the HTML form submits when a button is clicked. Is there a way to prevent this ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

Dynamic Resizing of Facebook Page Plugin for Responsive Design

I'm currently using the Page Plugin widget from Facebook. The Facebook page mentions: If you wish to adjust the widget's width when the window is resized, you must manually refresh the plugin. Is there a way to dynamically modify the width of ...

Using the for loop to asynchronously fetch data and access the finished result variable

Exploring the world of asynchronous JavaScript, I find myself pondering a question: how can I ensure that my code only starts working on a created array once all queries are completed? My current approach involves fetching pages in a for loop. Here's ...

Issue with adding a key:value pair to res.locals.object in Node/Express not functioning as expected

Currently, I am working on constructing an object within res.locals by executing multiple MongoDB operations and utilizing the next() middleware. Once I have added an object to res.locals, such as: res.locals.newObject, my goal is to subsequently add addi ...

Finding the precise XPath for a specific column title with C# and the Selenium WebDriver: A step-by-step guide

My dilemma is with the HTML snippet below, which I'm attempting to locate using XPath. Despite my efforts, the following code doesn't seem to be functioning as expected: <label class="ms-Label headerText-269" title="Reference Id ...

Discover the method for accessing a CSS Variable declared within the `:root` selector from within a nested React functional component

Motivation My main aim is to establish CSS as the primary source for color definitions. I am hesitant to duplicate these values into JavaScript variables as it would require updating code in two separate locations if any changes were made to a specific co ...

Conflicting Issues between jQuery Toggle and Mouseup Function

I have a straightforward button that, when clicked, toggles a menu. If the menu is expanded/visible, I want it to be hidden when clicking anywhere on the page (except for the menu itself). var menuBtn = $(".btn-menu"), menuContainer = $(".menu"), menuChi ...

The concept of selective importing within JavaScript

Seeking guidance on configuring conditional imports for a native library that is built for both node and electron. The challenge arises when one project requires the node implementation for testing, while another project needs the electron version. Projec ...

Capture a fragment of a scene and convert it into a unique texture using THREE.JS

I'm interested in creating a texture of a specific area in my scene, similar to the example shown in the official documentation for three.js framebuffer here. As I examine the code provided, there's one particular aspect that's unclear to me ...