After completing these activities you should be able to:
As part of Intro the World-Wide-Web (WWW) classes, we have covered web programming languages HTML and JS to provide a foundation into how information is processed from (inputs) and/or presented to the user (outputs). Manipulating data provided through both system and users serve a particular purpose, be it presenting information on a webpage or passing data to other systems that result in transactions or calculations. As a markup language, tags are identified by the browser to organize how data is presented by HyperText Markup Language (HTML). Starting from the top and working down, a web page is loaded once the code is received from a server. Because HTML is limited, JS can pick up where it falls short by invoking advanced programming structures and capabilities. We previously provided basic functionality into the user interface but with this lesson we are going to cover how web code is presented to the application users interact with, or the client-side.
When a user visits a website, such as https://www.archive.org, they enter a Uniform Resource Locator (URL) into the browser's address bar. The browser then sends a HyperText Transfer Protocol (HTTP) request to the server to retrieve the resource specified in the URL (e.g., a webpage). The server processes this request and responds with an HTTP response that includes the requested resource, along with a status code (such as 200 for a successful request or 404 when the resource is not found). There are multiple types of HTTP methods a client can use; GET and POST are among the most common.
(Note: The additional steps involved in making the request work, such as resolving human-readable URLs into IP addresses, will be covered later in the course.)
Take a look at the code used by your browser to render the page on the client-side. Open the webpage https://www.usna.edu/CyberDept/sy110/resources/student_renders/ex2.html and follow the instructions below:
The web pages primarily seen up to this point have been static web 1.0 pages. Content may look like it's changing but is done by loading different web pages. Here is a good example of a static webpage. Every link accessed loads a new web page and everyone looking at that page sees exactly the same thing. All but the most basic sites these days have dynamic content, which means that changes occur to the current page, with or without user interaction, and websites have pages that look different to different users. More complex websites, like Google Maps, are built around the idea of dynamic web content. The box on right is an example of a basic form of dynamic content. Click on the +'s and -'s and see what happens. Note that the URL address at the top of the page never changes!
Dynamic content is possible through the execution of a snippet of code called a script. The snippet of code can execute on either client machine (meaning in the web browser) or on the web server. So we can have either client-side scripting or server-side scripting. Scripts can also be either event or non-event driven. What this means is that the scripts can either run in response to user action, such as clicking on something (event driven), or can run automatically when the web page is loaded (non-event driven). The boxes with the +'s and -'s that you clicked on are event driven since you, as the user, had to take an action for the event to take place.
When thinking about whether the script is executing on the client machine or the server, there are some important considerations:
JS is a vital web language for businesses across the world and is also why it's the most popular as websites and mobile apps rely on distributing many services for users and consumers. JS is invoked in HTML code through the use of <SCRIPT> tags in order to embed scripts, with the type attribute, which identifies the language used:
<SCRIPT type="text/javascript">...</SCRIPT>
Document Object Model (DOM). The use of JS embedded scripts leverages DOMs, which is a World Wide Web Consortium (W3C) standard model and programming interface that defines HTML elements as objects, the properties of HTML elements, methods to access all HTML elements, and the events for all HTML elements. What does that mean? The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
Objects in programming languages are created and referenced as you would physical objects around you. There are tables and chairs in the classroom, all of which are objects that are referred to by names. Tables and chairs comprise of parts, such as legs and surfaces, but these parts or classes are different for each of the objects. Once the tables and chairs are assembled using the appropriate classes, these objects may now be referred to with actions, called methods for executing actions, such as move the table or sit on the chair. This series of statements within the classroom now establishes a function. As such, classes define properties of objects, objects are referenced in methods for moving, copying, manipulating, and storing data associated with objects, and functions are a series of statements that perform tasks but not associated with objects, like methods would be.
Structuring programming languages in this way allows for easy referencing and consistent processes for developers to build applications. The primary use of DOM in JS will be document in order to leverage the use of dynamic HTML. The DOM document will accomplish the following:
Within the document object in JS, document.write and document.location are examples that can depict the use of non-event driven scripts. These methods are not exclusive to non-event driven scripts but they will be employed in examples for event-driven scripts.
document.write sends data to HTML output and is used to insert text, elements, or a combination. Its usage and syntax uses the document object to manipulate HTML code.
document.write("Hello World") would print Hello World on the web page.document.write("<b>This is a bold element</b>") would insert the bold element in the parenthesis into the web page and the browser should render This is a bold element in boldface.With the ability to reference an object using JS, calculations can now be performed to write to a web page. The code below is an example of what can be accomplished with embedded scripts:
More examples of DOM object use of document.write are provided, along with its code. In ex0.html, a while loop is leveraged to write GONAVY to HTML output 1,000 times. What would be a tedious task has now been simplified with a few lines of code and is useful for iterative content.
| ex0.html (see how this page is rendered) | ex3.html (see how this page is rendered) | |
<html>
<head></head>
<body>
<script type="text/javascript">
var iter = 0;
while(iter < 1000)
{
iter = iter + 1;
document.write("G O N A V Y ! ");
}
</script>
</body>
</html>
|
<html>
<head></head>
<body>
<script type="text/javascript">
var iter = 0;
while(iter < 1000)
{
iter = iter + 1;
document.write('<span style="color: #ff0000">G O</span> <b>N A</b> V Y ! ');
}
</script>
</body>
</html>
|
|
| Short program, long web page! | Remember, document.write() allows us to insert arbitrary HTML code! So this time we've added formatting. |
A key consideration for the use of embedded scripts is when they are executed. The location of the script in the HTML file determines where the code appears, replacing <SCRIPT type="text/javascript">...</SCRIPT> when rendering in the browser and reading from the top, down.
Another method of the document object is document.location. This variable holds the URL for the current page. Enter
alert(document.location);into the interpreter field to the right and an alert box will pop up displaying the URL for this page. Setting the variable document.location to a new string value that contains a valid URL sequence causes the browser to load that page. Try entering the following code into the interpreter:
document.location = "https://www.westpoint.edu";If you've taken a detour and returned to this page, redirection to other websites is levergaged with the use of document.location. This is useful for redirecting users that may have bookmarked or linked an outdated page. Here's an example:
| redirect.html (see how this page is rendered) |
<html> <head></head> <body> <script type="text/javascript"> document.location = 'https://www.westpoint.edu'; </script> </body> </html> |
Most email clients allow you to write and read emails with HTML formatting, not just plaintext. Combining this with JavaScript allows for some malicious possibilities. For example, HTML can automatically send you to a different website without having to click on any links! If an email client executes JS embedded code in an HTML-formatted email, we can craft it in such a way that opening the email sends the machine's browser to a malicious website. You are safer with an email client that does not execute HTML or embedded JS!
All email clients allow attachments, to include HTML files. If the recipient opens the attachment, it will be rendered by the recipient's browser and will almost certainly execute JS! Thus, leveraging document.location to redirect the recipient to a malicious page. As long as the recipient opens the attachment, we can send them to any page — automatically.
Now that we have covered some common non-event driven scripts, we will learn to identify, understand, and write scripts for web pages that are event driven, meaning that the script executes when some action, typically initiated by the user, occurs. DOM methods covered will include document.getElementById, which allow us to gain access to a specific HTML field and change it after the web page has already been loaded and document.forms. There are two fundamental requirements we will cover that allow a comprehensive understanding of client-side scripting:
In order to manipulate HTML elements, the tags have to be identified using the id attribute. This ability to identify a specific HTML element is the key to allowing our event driven code to modify content within a web page, providing each user with an interactive experience. Once the HTML element has been identified, the document object can be invoked.
In HTML code. The HTML element is assigned an identifier using the id attribute. Two HTML elements below have been assigned an identifier, (1) <p> is assigned foo and (2) <b> is assigned bar. Another way of stating it, the line of code below assigns the id of "foo" to the paragraph element, whereas the id of "bar" is assigned to the bold element.
<p id="foo">The <b id="bar">quick</b> brown fox jumps over the lazy dog.</p>
The quick brown fox jumps over the lazy dog.
|
|
|
In this example, when you change the color of "foo" after changing "bar," the word "quick" inside "bar" does not change color. This occurs because "bar" has its own specific color set, which overrides the inherited color from "foo." In CSS, inheritance controls how styles are passed from parent elements to child elements. If desired, this behavior can be adjusted by modifying the CSS properties to ensure that changes to the parent element's style are reflected in its child elements.
Within JS, the object that's returned by this method can be manipulated in many ways. Every element has an .innerHTML value that stores whatever is between the start and end tags of the element. Every element also has an .style that contains values (of type string) for the many properties that affect the way an element looks in the browser. These .style properties have the ability to change the formatting of text displayed.
| .innerHTML stores whatever is between the start and end tags of the element as a string. If there are other elements nested within the string value, the .innerHTML will contain tags. |
|
| .style.color stores the color of the text. Colors are specified as RGB byte-values in hex, so "#FF0000" references the color red. |
|
| .style.background stores the background color. |
|
| .style.fontFamily stores the font type. You can specify a particular font, or generic fonts like: serif, sans-serif, monospace, cursive or fantasy. |
|
| .style.fontSize stores the size of the font. There are several variations for referencing units including pt (points), px (pixels) and em (multiple of current font-size, so 1em is the current font-size, 2em is twice the current font-size, etc). |
The events that we're most used to in web-browsing are mouse related — specifically with clicks. Any element can be given an onclick attribute whose value is a chunk of JS code to be executed whenever the mouse is clicked within that element. Here's an example (Note that document.body is a default HTML object without having to define an id):
| content | Code that makes it happen | |
|
Clicking anywhere within the bold text causes the text to go red! Refresh the page to return sanity. |
Clicking anywhere <b onclick='document.body.style.color="#ff0000"'>within the bold text</b> causes the text to go red! Refresh the page to return sanity. |
There are actually a number of mouse events that are scriptable this way via the following attributes:
The intent for learning document.getElementById in this course isn't to make interactive websites but to gain a better understanding of the cybersecurity issues associated with allowing scripting languages to run in our browser. In this section we build upon what we have learned above to better understand how redirection can be leveraged in malicious ways.
Obfuscation. What you see isn't always what you get. Because of the ability to run embedded scripts, the browser has the potential to mislead users into thinking certain actions will be conducted. Hover your cursor over the link to see what website is referenced in the status bar, then click on it to see where it actually takes you to.
<A id="foo" href="http://www.usna.edu"
onclick="document.getElementById('foo').href='http://www.youtube.com/watch?v=dQw4w9WgXcQ';">
www.usna.edu
</A>
Because the onclick script gets run before the browser reads the href attribute, that executes prior to the value in the href attribute. Quite sneaky, eh?
Don't click on anything and let your mouse pointer pass over the name: <SPAN onmouseover='document.location = "https://www.westpoint.edu/"'>Billy</SPAN>.The moral of this story is that we can easily manipulate web pages in unexpected ways.
| The interactive content | How it was done | |
|
Word Jumble Challenge: YGANOV show solution |
Word Jumble Challenge: YGANOV <span id="sol"></span><br>
<b id="inst" onclick='
if (document.getElementById("inst").innerHTML == "show solution") {
document.getElementById("sol").innerHTML = "→ GONAVY";
document.getElementById("inst").innerHTML = "hide solution";
} else {
document.getElementById("sol").innerHTML = "";
document.getElementById("inst").innerHTML = "show solution";
}
'>show solution</b>
|
In the JS class, the prompt(); function was used to solicit input from the user. This may be a useful way of learning about JS Input/Output (I/O) but it isn't practical or common. The use of HTML Forms are prevalent ways to solicit input from a web user. This part of the class is intended to demonstrate two learning outcomes:
| Text. Allows strings of characters to be read from the user. |
|
| Password. Masks the characters being typed to prevent anyone viewing the screen from observing what is being entered. |
|
| Radio. Allows the user to only select one item from a list. |
|
| Checkbox. Allows the user to select multiple items from a list. |
|
| Button. Allows actions to be conducted with the use of embedded scripts. |
<FORM name="input_types" onsubmit="return false;">
<p>The text input type is as follows:</p>
<INPUT type="text" name="text_field"><br><br>
<p>The password input type is as follows:</p>
<INPUT type="password" name="text_pswd"><br><br>
<h5>Radio Examples</h5>
<INPUT type="radio" name="text_radio1">radio1a
<INPUT type="radio" name="text_radio1">radio1b
<INPUT type="radio" name="text_radio1">radio1c
<INPUT type="radio" name="text_radio1">radio1d<br>
<INPUT type="radio" name="text_radio2">radio2a
<INPUT type="radio" name="text_radio2">radio2b
<INPUT type="radio" name="text_radio2">radio2c
<INPUT type="radio" name="text_radio2">radio2d
<h5>Checkbox Example</h5>
<INPUT type="checkbox" name="text_check1">check1a
<INPUT type="checkbox" name="text_check1">check1b
<INPUT type="checkbox" name="text_check1">check1c
<INPUT type="checkbox" name="text_check1">check1d
<h5>Button Example</h5>
<INPUT type="button" name="submit" value="Submit" onclick="alert('Thanks for
pushing my button!')">
<INPUT type="reset" value="Reset">
</FORM>
|
Input types can be used to solicit user data when visiting a website, serving as a foundation for many websites. Take a moment to reflect on any websites you had recently visited, how you interacted with the webpage, and if any of them had forms. Below is a form-based I/O used to perform calculations, resulting in converting two measurements of distance:
Conversion tool:
<FORM name="convert" onsubmit=> <INPUT type="text" name="feet" value="0" onchange=> feet = <INPUT type="text" name="inches" value="0" onchange=> inches </FORM>
Recall the conditional (if-else) example provided in the class lecture on providing a +/- grade based on a score. A simple form can be created to be published on the website. Design and efficiency is a factor when working with nested conditions but we'll build on the document.getElementById("grade") method to reference the INPUT type="text" name="grade" to update the field to reflect the appropriate +/- grade value.
|
|
<FORM name="grader" onsubmit="return false;">
<INPUT type="text" name="score" maxlength="3" size="6" value="0"
onchange="validate();">
</FORM>
<button onclick="grade(document.forms.grader.score.value);">grade</button>
<INPUT type="text" id="grade" maxlength="2" size="6">
<script>
function grade(score) {
if (score >= 93) {
document.getElementById("grade").value = "A";
} else if (score >= 90) {
document.getElementById("grade").value = "A-";
} else if (score >= 87) {
document.getElementById("grade").value = "B+";
} else if (score >= 83) {
document.getElementById("grade").value = "B";
} else if (score >= 80) {
document.getElementById("grade").value = "B-";
} else if (score >= 77) {
document.getElementById("grade").value = "C+";
} else if (score >= 73) {
document.getElementById("grade").value = "C";
} else if (score >= 70) {
document.getElementById("grade").value = "C-";
} else if (score >= 67) {
document.getElementById("grade").value = "D+";
} else if (score >= 60) {
document.getElementById("grade").value = "D";
} else {
document.getElementById("grade").value = "F";
}
if (score < 73) {
alert("MAPR Required");
}
}
</script>
|
| The process of converting scores into grades in this client-side script uses validation to help control input values for document.forms.grader.score.value. We do this by conditional statement that checks if score is <100 or >0 or is a number. Additionally, the maxlength attribute accepted by input text is limited to three. All other conditions fail and reset score back to a value of "0" if it is not met. |
<script>
function validate() {
if(document.forms.grader.score.value>100 ||
document.forms.grader.score.value<0 ||
isNaN(document.forms.grader.score.value)) {
alert('Invalid score');
document.forms.grader.score.value=0;
}
}
</script>
|