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");
Scrolling a Web Page:
If you want to scroll through a web page programmatically, you can use
JavaScript with window.scrollTo() or window.scrollBy().
Here's a basic example:
window.scrollBy(0, 500); // Scrolls down by 500px
If you need to automate scrolling to the bottom or top:
window.scrollTo(0, document.body.scrollHeight); // Scrolls to the bottom of
the page
2. Managing Multiple Windows:
You can open new windows programmatically using JavaScript with
window.open()
window.open("https://example.com", "_blank"); // Opens a new tab/window
with the specified URL
If you're working with multiple windows or browser tabs, you'll need to
reference these windows for interaction:
const newWindow = window.open("https://example.com", "_blank");
newWindow.document.write("<h1>New Window Content</h1>"); //
Manipulates content in the
3. Creating a Web Page in a New Window:
If you want to create or display content in a new window (e.g., a new
webpage), you can do so by opening the window and dynamically inserting
content. For example:
const newWindow = window.open();
newWindow.document.write('<html><head><title>NewPage</title></
head><body><h1>Hello, World!</h1></body></html>');
Using JavaScript in URLs, JavaScript security, and timers are important
concepts when it comes to web development and web security. Let me explain
each of these topics in detail.
1. JavaScript in URLs:
In the context of URLs, you may have seen JavaScript used in links, often in the
form of javascript: protocols. This is a type of "pseudo-protocol" that allows
JavaScript to execute directly when you click a link.
<a href="javascript:alert('Hello, world!')">Click me</a>
This will trigger an alert when the link is clicked. However, the use of JavaScript
directly in URLs is generally discouraged because it can create several security
risks, such as:
Cross-Site Scripting (XSS): If not properly sanitized, JavaScript in URLs
can lead to code injection vulnerabilities where malicious scripts can be
executed in the user's browser.
Phishing: Malicious websites may trick users into clicking on links that
execute dangerous JavaScript.
<a href="#" id="myLink">Click me</a>
<script>
document.getElementById('myLink').addEventListener('click', function(event) {
event.preventDefault();
alert('Hello, world!');
});
</script>
2. JavaScript Security:
JavaScript is a powerful tool but can also be a vector for security
vulnerabilities, especially when interacting with untrusted content. Some
common JavaScript security issues include:
a. Cross-Site Scripting (XSS):
XSS occurs when an attacker injects malicious scripts into web pages that are
viewed by other users. These scripts can steal cookies, session data, or perform
actions on behalf of the user.
Mitigation:
Sanitize inputs: Always sanitize user inputs and escape potentially
dangerous characters (e.g., <, >, ', ") before inserting them into the
HTML or JavaScript.
Use Content Security Policy (CSP): CSP is a security feature that helps prevent XSS attacks by
controlling which resources the browser is allowed to load.
Use libraries like DOMPurify: These can help clean user-generated content before it is
rendered in the browser.
b. Cross-Site Request Forgery (CSRF):
This occurs when an attacker tricks a user into performing actions (e.g., submitting a form)
without their knowledge or consent. JavaScript can be used to trigger such requests on
behalf of a user.
Mitigation:
Use anti-CSRF tokens in forms or AJAX requests.
Ensure that sensitive actions require authentication and verify that the
request is legitimate.
c. Same-Origin Policy:
The Same-Origin Policy (SOP) is a security measure implemented by web
browsers to prevent web pages from making requests to a domain
different from the one that served the web page.
Mitigation:
Cross-Origin Resource Sharing (CORS) is a mechanism that allows
controlled access to resources on a web page from another domain. It
must be configured on the server for cross-origin requests.
d. JavaScript Libraries and Frameworks:
Always use up-to-date versions of popular libraries and frameworks.
Older versions might have known vulnerabilities.
3. Timers in JavaScript:
Timers are used in JavaScript to perform actions after a certain period of time
or repeatedly. JavaScript provides two main timer functions: setTimeout() and
setInterval().
a. setTimeout():
This function allows you to delay the execution of a function by a specified
amount of time.
Example:
setTimeout(function() {
alert('This message is shown after 3 seconds');
}, 3000); // 3000 milliseconds = 3 seconds
b. setInterval():
This function allows you to execute a function repeatedly at specified intervals
(in milliseconds).
Example:
setInterval(function() {
console.log('This message is logged every 2 seconds');
}, 2000); // 2000 milliseconds = 2 seconds
c. Clearing Timers:
You can clear timers to stop their execution using clearTimeout() or
clearInterval().
Clear a Timeout:
let timeoutId = setTimeout(function() {
console.log('This won\'t execute because we will clear the timeout');
}, 5000);
clearTimeout(timeoutId); // Cancels the timeout
Clear an Interval:
let intervalId = setInterval(function() {
console.log('This message will stop logging');
}, 1000);
clearInterval(intervalId); // Stops the interval
Conclusion:
JavaScript in URLs should be avoided, as it can introduce significant
security risks such as XSS.
JavaScript Security is crucial, and you should always sanitize inputs,
implement secure coding practices, and ensure that security measures
like CSP and CORS are properly configured.
Timers (setTimeout and setInterval) are useful tools in JavaScript for
scheduling tasks, but they should be used with care to avoid
performance problems and potential bugs.
Browser Location and History:
browser location and history are two essential concepts that influence the
user's experience and functionality of websites. Understanding how to manage
both is crucial for creating intuitive, responsive, and user-friendly web
applications. Here's an overview of both:
1. Browser Location (Geolocation)
Browser location refers to the geolocation of the user, which can be accessed
using the browser’s geolocation API. This allows websites to determine the
user’s geographic location (latitude, longitude, altitude, etc.) to provide
personalized content or services based on the user’s location.
Use Cases:
o Maps and Directions: Providing users with map services or
location-based directions (e.g., Google Maps).
o Local Content: Showing nearby stores, restaurants, or weather
forecasts.
o Personalization: Customizing content such as news or events
based on a user's location.
How It Works: The browser uses a combination of methods to
determine the user’s location, such as:
o GPS (Global Positioning System): The most accurate, typically
used on mobile devices.
o IP Address Geolocation: Approximate location determined from
the user's IP address.
o Wi-Fi or Bluetooth Networks: Using nearby networks to
triangulate the user's location.
JavaScript API: The Geolocation API in JavaScript is used to access the
user’s location:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log("Latitude: " + latitude + " Longitude: " + longitude);
});
} else {
console.log("Geolocation is not supported by this browser.");
o The getCurrentPosition() method gets the user’s current position.
o The method can take two callback functions: one for success (with
the position data) and one for failure (when geolocation is not
available or allowed).
Permissions: Browsers ask users for permission to access their location,
and they can deny or allow it. It’s essential to respect privacy and inform
users about why their location is needed.
2. Browser History
Browser history refers to the history of URLs that a user has visited in their
web browser. Managing browser history is important for controlling navigation
flow and creating a smooth user experience on modern, dynamic websites.
Use Cases:
o Navigation: Allowing users to go back and forth between pages in
a single-page application (SPA).
o State Management: Storing state information in the URL to allow
the user to return to a specific page or state later (e.g., search
filters or form data).
o SEO: Ensuring that each page or content state has a unique URL,
helping with search engine optimization and better user indexing.
How It Works:
o History API: The History API allows developers to manipulate the
browser's history. This is useful in SPAs where traditional page
reloads aren't used, but users need to be able to go back and forth
using the browser’s back and forward buttons.
Methods:
o pushState(): Adds a new entry to the browser history stack
without reloading the page.
window.history.pushState({ page: 1 }, "Title 1", "?page=1");
o replaceState(): Updates the current history entry without creating
a new one.
window.history.replaceState({ page: 2 }, "Title 2", "?page=2");
o onpopstate event: Triggered when the active history entry
changes (e.g., when the user clicks the browser's back or forward
button).
window.onpopstate = function(event) {
console.log("State: ", event.state);
};
Session vs Persistent History:
o Session History: Keeps track of navigation within a single session
(until the browser is closed).
o Persistent History: Refers to the full history that stays even after
the browser is closed and reopened, usually stored in the
browser.
Benefits:
o Smooth User Experience: By manipulating history without page
reloads, users can seamlessly navigate through different states in
a web application.
o Back and Forward Navigation: Users can use the browser's built-
in back and forward buttons to navigate between states in SPAs.
o Link Sharing: Unique URLs for different application states allow
users to share links that load the application in a specific state.
Key Differences Between Browser Location and Browser History:
Purpose:
o Browser location is about identifying the user's physical location,
while browser history pertains to the navigation path taken by the
user on the website.
Interaction:
o Location is user-dependent and may require user consent. History
is controlled by the website or web application, with some
interaction from the user.
Usage:
o Geolocation is typically used for location-based services, while
browser history is used for navigation and managing application
states.
Conclusion:
Understanding both browser location and history is crucial in modern web
design. Location services can enhance the user experience by providing
personalized content based on the user’s physical location, while managing
browser history is key to creating seamless navigation in SPAs.