Client-Side Scripting

client-side coding scripting js scripts

Client-Side Scripting is a technique where code, along with an HTML web page, is sent to the client by the server. In simpler terms, it allows scripts to run directly in the user’s browser without connecting to the server.

Including JS

Internal

When including JavaScript internally the code runs when the browser gets to it in a chronological order. So if the script is in the head it will fire before the content has loaded and if its before the body tag it will fire after. this becomes important when JS plugins are used like jQuery which other plugins require, if they are not loaded in order then code will not work. A disadvantage for loading internal JS is that it cannot be duplicated to other pages including modifications. If it’s small amounts of JS then using it internally can be beneficial if its only needed on a single page as you can work in a single document.

<script>
    alert("test");
</script>

External

When including a extensive functions sheet it’s best practice to do so externally just like CSS. This is to not only split the different uses of the code to make it easier to understand but also reduce the size of the html document, if a large amount of js code is internal then it makes html code below it difficult to edit as you have to scroll through js. Also many scripts are not just suited to a single page meaning if each page linked to the external functions sheet no code duplication is required.

<script src="functions.js"></script>

Characteristics

The Nature of the Language

JavaScript is dynamic and functional. JS makes up the web platform by allowing interactivity to webpages in an object oriented fasion. The core functions of JS is the posibility to add, remove and manipulate content in the DOM (Document Object Model). Becuase JS allows for variables and objects to have their properties dynamially update and change this allows for realtime interaction without the page reloading, the adition to AJAX support means that modern web2.0 sites can have any and all interaction done without having the website reload.

JS is known as a multi-paradigm language because it allows for coding in the following paradigms: scripting, object-oriented, imperative and functional.

var temp = prompt("This is a prompt box", "");
alert(temp);

The Concepts of Objects and Methods

In JavaScript, an object is a standalone entity, with properties and type. Objects in JS have associated properties, these properties can be explained via variables within the object. These variables define the characteristics of the object and are accessed via the dot notation.

User defined objects allow for arrays of values to be both set and get using JS. Objects allow for multiple instants of the same object however with different properties. This would be useful for a car trading site where each car will require the same properties but with different values, say a Fiat 500 will have varied specifcations compared to a Ford Focus. Below is an example of an object being set.

var objectName = {
    propertyName: "value",
    anotherPropertyName: "value"
};

These code samples show how the data from the object can be retrieved from the object in two seperate ways.

alert(objectName.propertyName)
alert(objectName["propertyName"])

Methods can also be included in objects for the same reasons as properties. Below is how they are set and get.

var objectName = {
    propertyName: "value",
    anotherPropertyName: "value",
    methodName : function() {
        return this.propertyName;
    }
};
alert(objectName.methodName())

JS Methods are functions stored as object properties which can be preformed on objects. As well as allowing for objects to be created there is also built in functions using the window and document object name. An example of one is cookies.

document.cookie

Event Handling

Within HTML, events are ‘things’ that occur in the DOM. JavaScript can ‘react’ to these events produced and modify the DOM. Like in the example the function is being called on clikc instead of the code being called, this is because normally JavaScript is multi lines long so would be untidy to do so all on one long line or make the onclick attribute take up more than one line in the HTML.

<button onclick="displayAlert()">alert()</button>
function displayAlert() {
    alert(""This is an alert box"");
}

Security Issues

Because JavaScript is a client side language these means that it is not able to interface with the server however it can still be the cause of many security issues. Because it is ran on the client side and not server it can be modified and re-ran with any code provided by the client, meaning that the code can be modified for malicious intent or data theft. Because of this validation must be atleast done on the server so it cant be bypassed however for UX reasons its recommended to do both client and server validation.

Cross-Site Scripting (XSS) is the most common exploit for JavaScript. XSS enables attackers to manipulate websites using JS to display and run malicious JS code to its users. This is possible if browsers dont have origin policys implemented. A well known XSS which happened on Twitter was the auto retweet exploit. It consisted of JS code that forced the user to automatically retweet the tweet if it appeared on their timeline and like a row of dominos procceeded from there. The reason XSS is possible is only when a website directly echos out something that the user enters without parsing it without replacing tags (<>) with their Unicode counterparts.

Cross-Site Request Forgery (CSRF) allows for attackers to gain access via cookies of other users browser sessions. This is possible only when the authentication request is soley done via cookies. Both CSRF and XSS are in the Application Layer and can result in data theft, fraud and tampering of the users browser. Both can be prevented if the developer implements the neccessery safewalls inplace.

Access Methods

Each of the following methods returns an object. The object or objects which is selected depends on the method used. Objects can be selected using either: a class, a id, a tag or via css selectors. The CSS selectors allows for the first of a kind of tag/class/id or the last or anything inbetween.

document.getElementById()
document.getElementsByClassName()
document.getElementsByTagName()
document.querySelector()
document.querySelectorAll()

Functions

Alert, Confirm and Prompt Boxes

In the early days of JavaScript, Alerts, Confirms and Prompts were highly used as they were a easy and unified way to either present or recieve data to/from the user. However, since the web2.0 movement these functions are no longer the leader as any sites favour custom elments to conincide with their overall site look.

Alert

The alert function can display ASCII data to the user via a native browser window, while this can be not only useful but also look proffesional on modern browsers (Safari) on others the native functions have yet to be redesigned so still look outdataed when used. Also alerts can be used to prevent the user from using their browser as many rogue sites do to show either advertisements or warnings about how your machine has multiple virus.

alert("This is an alert box");

Confirm

The confim function displays a dialog box with the possibility to have a custom message also displayed. Similar to the alert function it disables all other program use until it is dismissed. It can be used in an if statemant which is its primary use as it reutrns true/false dependednt on wether the user clicked ‘Ok’ or ‘Cancel’.

confirm("This is a confirm box");

Prompt

Similar to the confirm dialog the prompt does the same duty in requireing data from the user however instead of a simple true/false output it uses a text field. As mentioned above however, this is far less used compared to custom onsite forms as they allow for styling and dont restrict browser usage while inputing data.

var temp = prompt("This is a prompt box", "");
alert(temp);

These built in browser functions add increased functionality to a webpage allowing for a developer to use system styled forms to either display or retrieve data. Although recently their use is started to decline in favour of custom built varients to match the sites asthtics not the clients system, they are still in use and allow for users to quickly and efficently input or recieve outputted data to/from a website.

User Redirection

Websites which arnt heavily relient on AJAX will need to be redirected to other webpages and when this is required its posible to do so using the window object and location function. This allows for seperate windows to be opened as well as addition tabs or simply the current window altered to a new URL address.

window.location = "http://www.google.com";

Using the window object to redirect a client to a seperate URL is functional for transfering data to/from another file or site as well as allowing for it to be done natively from JS and not requireign an interface to another language to do so, say headers in PHP.

Browser Detection

Sometimes it can be useful to know what the users machine is and what it supports. All this information can be sused out by using the navigator object. Below is a list of the most popular which are used to understand the usecase the client is in. However, this can never be 100% due to how many browsers work. Browsers use an engine which is what proccess the files to a site, the chromeium engline is not only used by Google Chrome but also Opera and Vivaldi meaning those browsers will apear as Google Chrome.

document.getElementById("browser-info").innerHTML = "<br><b>navigator.appCodeName: </b>" + navigator.appCodeName + "<br><b>navigator.appName: </b>" + navigator.appName + "<br><b>navigator.appVersion: </b>" + navigator.appVersion + "<br><b>navigator.platform: </b>" + navigator.platform + "<br><b>navigator.product: </b>" + navigator.product + "<br><b>navigator.language: </b>" + navigator.language;

Browser detection can add functionality to a website by knowing your specific browser and operating system brand/version a website can cater its content to you. This could be a plugin author creating a install button for his browser specific plugin or a software site defaulting to your operating system version of their package.

Cookies

JavaScript Cookies allow for small amounts of data to be saved onto the clients system similar to session data but can stay beyond program restarts and whole system reboots. These can be used to store data like wether they have seen a splash screen before to session keys for remember login systems. A site shouldnt require cookies only use them as optional resources as many systems have them disabled or do not support the standard. The values a cookie store is the path (Where the cookie is stored on the users drive), the TTL or Time To Live and the name/value.

var cookieName = prompt("Specify cookie value", "");
document.cookie = ""exampleCookie="" + cookieName;
var exampleCookie = document.cookie;
alert(exampleCookie);

Cookies allow for offline storage of website data, this normally adds functionality like remember my username to online services by storing an encrypted key which is matched to a database which the loads to requested data to the user. This functionality helps users login in quicker without reducing the security level (to online asalients).

Compatibility

Much like CSS, JavaScript hast to be interpreted by the browsers engine to run the scripts. Much like the issues with CSS each browser has a different implementation of the JS interperater. This causes outdated browsers to not support the latest versions of JS as well as different browsers not suppoting certain elements either out of deisregard or purposfully because of security risks. Another issue can be when newer JS technologies are implemented and can conflict with HTML/CSS causing stability issues. Also, even if the browsers get updated to support the latest version of JavaScript, this doesn’t mean that the user will update their browser or that the browser has automatic updates enabled. Another issue that can arrise is many businesses disable JavaScript for their employees to protect the system from exploits. An example is in the latest HTML/JS specification, the type attribute is no longer required, this is great for oder sites as its less for the developer to code however if its not included then older sites and browsers will become desipricaded and fail to load scripts.

<script type="javascript" src="functions.js"></script>

Because each version of Interet Explorer is still used to this day in many different usecases and businesses many sites have specific function sheets for each version, this is where HTML Conditional Comments come into play. These are regular comments however have a if statement which can detect the version of Internet Explorer that is being used.

<!--[if lt IE 7]><![endif]-->
<!--[if IE 7]><![endif]-->
<!--[if IE 8]><![endif]-->
<!--[if IE 9]><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><!--<![endif]-->

Internet Explorer 11 includes a Compatibility Mode designed to reduce compatibility issues between browsers and help website render correctly and function properly with the latest and greatest JS/HTML/CSS technologies.

Previous Post Next Post