the JavaScript code Linked Scripts Event handlers The script must comply with HTML rules Note that script in Linked Scripts Event handlers The script must comply with HTML rules Note that script in

Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript and Client-side Scripting

Similar presentations


Presentation on theme: "JavaScript and Client-side Scripting"— Presentation transcript:

1 JavaScript and Client-side Scripting
Martin Kruliš by Martin Kruliš (v1.4)

2 The script must comply with HTML rules
Revision Embedded Scripts <script type="text/javascript"> the JavaScript code </script> Linked Scripts <script type="text/javascript" src="url"></script> Event handlers <img src="url" onmouseover="code-handling-event"> The script must comply with HTML rules Note that script in <script> element (both inline and referenced) is executed immediately after parsing the element/loading the external file. There are attributes like async or defer, which can affect this behavior; however, it is better not to rely on the entire DOM being constructed. by Martin Kruliš (v1.4)

3 Document Object Model …
Revision body h1 p img Document src DOM Example Document Object Model … alt html Document Object Model <html> <body> <h1>DOM Example</h1> <p> Document Object Model is an API … </p> <img src="url" alt="text"> ... </body> </html> by Martin Kruliš (v1.4)

4 Revision Document Object Model Object model representing HTML/XML tree
Class of each node corresponds with the node type Different nodes allow different methods Node Comment Text Element Document Attr CharacterData by Martin Kruliš (v1.4)

5 Revision Event Model Top-level scripts are executed immediately
Other code can be attached to various events One event loop processed in single thread Some events (e.g., clicking on a hyperlink) may have default actions default If the event is not stopped, it bubbles up DOM Tree Processes one event at a time Mouse Moved User Clicked Event Queue Dispatcher Loading Finished Target Window Resized Target element is found and the event handler is executed by Martin Kruliš (v1.4)

6 AJAX Asynchronous JavaScript and XML
A technique that combines three technologies JavaScript Asynchronous HTTP client API integrated in browser XML or other semi-structured data format Script invokes HTTP transfer Providing URL, method, callbacks, … The callback is invoked asynchronously At the conclusion of the HTTP transfer It may process the returned data (e.g., update the contents of the web page) by Martin Kruliš (v1.4)

7 AJAX XMLHttpRequest Object var httpReq = new XMLHttpRequest();
httpReq.open("GET", "index.php?ajax=1", true); httpReq.onreadystatechange = function() { if (httpReq.readyState != 4) return; if (httpReq.status == 200) processResponse(httpReq.responseText); else handleError(httpReq.status); } httpReq.send(); - The third argument of open() is async flag. If false, the send() call will block (very unwise). - XMLHttpRequest also has responseXML property, where the XML DOM is stored. - readyState values: 0 = not initialized, 1 = connection established, 2 = headers received, 3 = downloading response, 4 = operation completed More at In HTML5 APIs, the XMLHttpRequest is being replaced with fetch() API ( by Martin Kruliš (v1.4)

8 JSON JavaScript Object Notation (JSON) Syntax
Lightweight interchange format for structured data Based on subset of JavaScript language Otherwise language independent Many parsers exist with frontends for many languages Intended for replacing XML in simple scenarios Syntax Two basic structures: collections and lists Supports strings, numbers, bools, and null type Unicode safe by Martin Kruliš (v1.4)

9 JSON JSON Example [ { "StudentId": 42, "Name": "John Smith" },
"Name": "Jane Johnson", "Graduated": true } ] Ordered list Number (int) Unicode string Named collection Boolean literal by Martin Kruliš (v1.4)

10 JSON Applications in JavaScript
Mainly for transfer of JavaScript structures AJAJ – Asynchronous JavaScript and JSON Parsing var res = eval(jsonString); Fast but not safe (the string may contain malicious code) var res = JSON.parse(jsonString); JSON object was originally implemented in library and later added to ECMAScript 5 standard Serialization var jsonString = JSON.stringify(jsObject); Historical decision JSON is used often than XML. However, the acronym AJAJ is not very popular and most people talk about AJAX even when there is no XML involved. Example 1 by Martin Kruliš (v1.4)

11 Script Injection Attack
... find session ID ... ... send it over HTTP ... </script> Malicious script gets executed in Admin’s web browser (i.e., in Admin’s context/session) Attacker’s Browser Admin’s Browser Registration Admin Interface List of Users Name: Kapslík <script>...</> Fufník Submit Database by Martin Kruliš (v1.4)

12 Cross-site Scripting Problem
User injects malicious JavaScript into regular data fields (registration form, body, …) The field is displayed to another user -> the script may steal his/her identity Prevention Browser blocks HTTP requests to other domains Browser hides secured cookies from the script Programmer’s Discipline All user inputs must be tested or sanitized by Martin Kruliš (v1.4)

13 Fetch API New API for AJAX fetch(input[, init])
input – URL or Request object init – object with initialization parameters method – HTTP method to be used headers – request headers body – request body Returns a promise Promises are async. objects designed to replace callbacks by Martin Kruliš (v1.4)

14 Promises Promise Represents eventual completion/failure of async. operation (e.g., AJAX request) Easy chaining .then(fnc) – function called on success fetch(url).then(response => ...) .catch(fnc) – function called on error .finally(fnc) – called on completion (success or error) Aggregation Promise.all([ promise1, promise2, … ]) Promise.race([ promise1, promise2, … ]) If promise then()/catch() return also a promise object, the promises can be chained Example 2 by Martin Kruliš (v1.4)

15 Promises How promises work
var p = new Promise((resolve, reject) => { window.setTimeout(() => { resolve('foo'); }, 300); }); p.then(value => { console.log(value); // outputs "foo" by Martin Kruliš (v1.4)

16 Form Data Wrapper for Form Data Can be used as body for AJAX requests
Assembled manually or loaded from <form> new FormData([ formElement ]) keys(), values(), entries() has(), get(), getAll() set(), append(), delete() by Martin Kruliš (v1.4)

17 HTML5 APIs History Non-visible Data Attributes
New feature – script state (history.state) history.pushState(), history.replaceState() Captures hidden script-managed state Allows backward/forward navigation over the states Non-visible Data Attributes Data for scripts, but associated with DOM elements Special data-* attributes (e.g., data-foo-bar) Appear in element.dataset collection Ad example above – element.dataset.fooBar Some of the APIs have separate specifications in the terms of W3C standardization, but they are close to HTML5. Thus, we will not distinguish explicitly the HTML5 specification from the related APIs specifications. by Martin Kruliš (v1.4)

18 HTML5 APIs Data Storage Web Workers
Persistence data storage accessible from JS Key-value database Similar isolation like cookies LocalStorage – persistent, per web application SessionStorage – for each window/tab Web Workers Background workers executing JS code Utilizing multiple cores Communicate by messages with main loop by Martin Kruliš (v1.4)

19 Compatibility Issues Coding with Multi-browser Support
Browsers developers implement the web standards when they want and how they want Especially problematic with their older versions Test the functionality, not the browser type/version if ("XMLHttpRequest" in window) { AJAX code } else { no AJAX } Use libraries Babel – JS transpilling and polyfill Webpack – bundling the code (JS and CSS) Example – to compare features of various browsers see List of some intriguing JavaScript libraries can be found here or here by Martin Kruliš (v1.4)

20 jQuery jQuery Library Modern JavaScript library for basic operations
Easy to learn and use Lightweight footprint Supports almost all currently used browsers Key features Simplified DOM traversal and manipulation Event handling CSS based animations and effects Unified AJAX API with support for data (de)serialization Extendable with plugins and UI libraries by Martin Kruliš (v1.4)

21 jQuery Object jQuery Object “Select and Do” Philosophy
Function object in global name jQuery and $ Acts as a function that returns set of nodes and as a container object for library functions “Select and Do” Philosophy Select a set of DOM nodes Apply (a sequence of) operation(s) on the whole set of selected nodes Most methods support invocation chaining $(selector).doIt().doAnother().doSometingElse(); by Martin Kruliš (v1.4)

22 jQuery Selectors Selector Selects set of DOM nodes for further usage
$("selector") or $(DOMnode) or $("HTMLfragment") jQuery Selectors are inspired by CSS3 selectors "div" – select elements of given name "#id" – select element by its ID ".class" – select elements with specific CSS class "ancestor descendant" – express DOM relations :disabled, :visible, :checked, … Subsequent operations work on the whole set $(".secret").hide(); by Martin Kruliš (v1.4)

23 jQuery DOM Manipulation
Manipulating HTML Structure Wrappers for DOM manipulation functions prepend(), append(), before(), after() – insert content before/after inside/outside selected elements remove(), empty(), detach() – remove (child) nodes replaceAll(), replaceWith() html(), text() – manipulate with content clone() – create a deep copy of the element attr(), prop(), removeAttr(), removeProp() Attr ~ HTML attributes, prop ~ properties (checked, …) Reading methods take only the first element in set by Martin Kruliš (v1.4)

24 Discussion by Martin Kruliš (v1.4)


Download ppt "JavaScript and Client-side Scripting"

Similar presentations


Ads by Google