0% found this document useful (0 votes)
21 views

Module4

How to set cookie in browsers by sp

Uploaded by

prateekcmsstroad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Module4

How to set cookie in browsers by sp

Uploaded by

prateekcmsstroad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Module -4

What is cookies?
In JavaScript, cookies are small pieces of data that are stored on the user's
browser. These cookies are often used for tracking, storing session
information, user preferences, and other data that needs to persist across
different pages or sessions. JavaScript provides simple methods to work with
cookies.

A cookie is an amount of information that persists between a server-side and a


client-side. A web browser stores this information at the time of browsing.

Basic Cookie Operations in JavaScript:


1. Setting a Cookie: To set a cookie in JavaScript, you can assign a string to
document.cookie. This string should include the key-value pair and other
optional parameters such as expiration time, path, and domain.
// Set a cookie with key "user" and value "JohnDoe"

document.cookie = "user=JohnDoe";

Setting a Cookie with Expiration: You can specify the expiration date of a
cookie. If the expires attribute is not set, the cookie will expire when the
session ends (i.e., when the user closes the browser).
// Set a cookie that expires in 1 day
const expires = new Date();
expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000)); // 1 day in
milliseconds
document.cookie = "user=JohnDoe; expires=" + expires.toUTCString();

Setting a Cookie with Path and Domain: You can specify a path for which the
cookie is valid. By default, cookies are only available to the page that created
them, but you can extend the scope with the path attribute.
document.cookie = "user=JohnDoe; path=/; expires=" + expires.toUTCString();

you can also set the domain attribute to specify for which domains the cookie
is available.
Reading a Cookie: To read a cookie, you can simply access document.cookie.
However, document.cookie returns all cookies in a single string. You'll need to
parse it manually.
// Function to get a cookie value by name

function getCookie(name) {

const value = `; ${document.cookie}`;

const parts = value.split(`; ${name}=`);

if (parts.length === 2) return parts.pop().split(';').shift();

// Get the "user" cookie value

const user = getCookie('user');

console.log(user); // Output: JohnDoe

Deleting a Cookie: To delete a cookie, set its expiration date to a past date.
This effectively invalidates the cookie.

// Delete the "user" cookie by setting its expiration date to the past

document.cookie = "user=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

Example Code:

// Set a cookie

function setCookie(name, value, days) {

const expires = new Date();


expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000)); // Convert
days to milliseconds

document.cookie = `${name}=${value}; expires=${expires.toUTCString()};


path=/`;

// Get a cookie

function getCookie(name) {

const value = `; ${document.cookie}`;

const parts = value.split(`; ${name}=`);

if (parts.length === 2) return parts.pop().split(';').shift();

// Delete a cookie

function deleteCookie(name) {

document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC;


path=/`;

// Example usage

setCookie("username", "JohnDoe", 7); // Set "username" cookie for 7 days

console.log(getCookie("username")); // Read the "username" cookie

deleteCookie("username"); // Delete the "username" cookie

Notes:
 Cookie Size: Cookies are limited in size (about 4KB per cookie).
 Security: Be cautious with sensitive data in cookies, as they can be
intercepted by malicious users if not secured.
 SameSite Cookies: You can control cross-site request handling using the
SameSite attribute to prevent CSRF attacks.

 Here’s a simple guide to create, read, write, and delete cookies


using JavaScript. Each of these functions works by interacting
with document.cookie.
 1. Create (Set) a Cookie:

 To set a cookie, you can use the document.cookie property. A


cookie can have a name, value, expiration date, path, domain,
and security flags.
 2. Read a Cookie:

 To read a cookie, we need to access document.cookie. However,


this returns a string of all cookies, so we'll need a helper
function to extract the value of a specific cookie.
 3. Delete a Cookie:

 To delete a cookie, you can set its expiration date to a past


date, which will cause the browser to discard it.
 Complete Example with Functions for Setting, Getting, and
Deleting Cookies:
// Function to create (set) a cookie

function setCookie(name, value, days) {

const expires = new Date();

expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000)); // Set


expiration time (in milliseconds)

document.cookie = `${name}=${value}; expires=${expires.toUTCString()};


path=/`;
}

// Function to read a cookie value

function getCookie(name) {

const value = `; ${document.cookie}`; // Adding ; to avoid issues at the start


of the cookie string

const parts = value.split(`; ${name}=`); // Split cookie by the given name

if (parts.length === 2) return parts.pop().split(';').shift(); // Return the cookie


value

return null; // Return null if cookie not found

// Function to delete a cookie

function deleteCookie(name) {

document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC;


path=/`; // Set expiration to a past date

// Example usage

// Create (Set) a cookie named "user" with value "JohnDoe" for 7 days

setCookie('user', 'JohnDoe', 7);

// Read the cookie value

console.log(getCookie('user')); // Output: JohnDoe


// Delete the cookie named "user"

deleteCookie('user');

// Try to read the cookie again after deleting it

console.log(getCookie('user')); // Output: null


 Setting a Cookie (setCookie function):
 This function sets a cookie with the given name, value, and an optional
expiration time in days.
 The expiration date is calculated by adding the specified number of days
to the current time.
 The cookie is set with the path=/ attribute to make it accessible across
the entire domain.
 Reading a Cookie (getCookie function):
 The getCookie function looks for a specific cookie by name and returns
its value.
 If the cookie is not found, it returns null.
 Deleting a Cookie (deleteCookie function):
 To delete a cookie, we set the cookie's expiration date to a date in the
past (Thu, 01 Jan 1970 00:00:00 UTC).
 The path=/ attribute ensures that the cookie is deleted across the entire
domain.
Notes:
 Cookies are limited in size (about 4KB per cookie).
 Cookies without an expires or max-age attribute will expire when the
browser session ends.
 If you don’t specify the path or domain, cookies are by default available
to the page that set them.

Browser :
 In JavaScript, you can interact with the browser window by opening new
windows, giving them focus, setting their position, changing their
content, and closing them. Below is an example that demonstrates these
tasks:
 1. Opening a New Window

 You can use the window.open() method to open a new window. This
method takes several parameters to control the window's
characteristics.
 2. Giving the Window Focus

 Once the new window is opened, you can use the focus() method to give
the window focus.
 3. Changing the Window's Position

 You can control the position of the new window by using the
window.moveTo() method. This method allows you to specify the x and y
coordinates of the window.
 4. Changing the Content of the Window

 You can access the content of the new window and modify it by using
document.write() or other DOM manipulation methods.
 5. Closing the Window

 To close the window, you can use the window.close() method.


 Here's a complete example to demonstrate all of these actions:

// 1. Opening a new window

let newWindow = window.open("", "newWindow", "width=500,height=500");

// 2. Giving the window focus

newWindow.focus();
// 3. Changing the position of the window

newWindow.moveTo(100, 100); // Move the window to x=100, y=100 position


on the screen

// 4. Changing the content of the window

newWindow.document.write("<h1>Welcome to the New Window</h1>");

newWindow.document.write("<p>This is some dynamic content in the new


window.</p>");

// Add a button in the new window to close it

newWindow.document.write('<button onclick="window.close()">Close
Window</button>');

// 5. Closing the window after 5 seconds (you can manually close it too)

setTimeout(() => {

newWindow.close();

}, 5000); // The window will automatically close after 5 seconds

Explanation:

1. Opening a New Window:

o window.open("", "newWindow", "width=500,height=500") opens


a new window with no content (empty string) and sets its width to
500px and height to 500px.
o The second parameter ("newWindow") is the name of the window
(this is optional but can be useful if you want to refer to it later).

2. Giving Focus to the Window:

o newWindow.focus() gives the newly opened window focus,


meaning it will come to the front if it isn't already active.

3. Changing the Position:

o newWindow.moveTo(100, 100) moves the window to the position


(x=100, y=100) on the screen.

4. Changing the Content:

o newWindow.document.write("<h1>...</h1>") writes HTML


content to the new window.

o We also added a button with an onclick event to allow the user to


close the window manually.

5. Closing the Window:

o newWindow.close() is called inside a setTimeout to automatically


close the window after 5 seconds. You can also call window.close()
manually by triggering the button action in the new window.

Important Notes:

 Popup Blockers: Most modern browsers block popups or windows


opened without user interaction. You may need to ensure the new
window is triggered by an action like a button click.

 Window Features: When opening a window, you can specify additional


features in the third argument of window.open(), such as resizable,
scrollbars, toolbar, and others. Example:

let newWindow = window.open("", "newWindow",


"width=500,height=500,resizable,scrollbars");

You might also like