Presentation is loading. Please wait.

Presentation is loading. Please wait.

Client-side Scripting

Similar presentations


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

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

2 Client-side Scripting
Including Scripts into Web Pages Dynamic modifications of HTML and CSS Handling user actions within the browser Asynchronous communication with server Major Challenges Security The script is completely isolated from the computer It may interact only through the browser Performance Limited due to properties of scripting languages and security measures imposed by the browser by Martin Kruliš (v1.1)

3 Client-side Scripting
Application Examples Improving esthetic experience of the presentation (beyond CSS capabilities) User input processing and verification Background data retrieval and synchronization Generating graphics (SVG or with the canvas element) Technologies JavaScript – dominating in current web applications VBScript – used in MSIE in the past 3rd party technologies (Flash, Silverlight, …) Examples Examples: by Martin Kruliš (v1.1)

4 The script must comply with HTML rules
JavaScript in HTML 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.1)

5 JavaScript in Web Browser
Browser Environment Global object window API for current browser window/tab Presents the global context Encapsulates all prepared objects and APIs window.document – DOM API for HTML document window.location – Access/control current URL window.history – Navigate through browser history window.screen – Information about system screen window.navigator – Information about the browser Controls the pop-up message boxes by Martin Kruliš (v1.1)

6 Document Object Model …
Accessing Document 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.1)

7 Accessing Document 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.1)

8 Accessing Document DOM Level
Incremental standards for DOM issued by W3C Level 0 Various technologies before standardization Sometimes also denoted DHTML (dynamic HTML) Level 1 – basic navigation and manipulation Level 2 – added namespaces, events, and CSS Level 3 – keyboard events, XPath, load and store Level 4 – being developed Browsers support entire level 1 and most of 2 and 3 DOM support and compatibility is a big issue in JS client-side scripting. Most application tend to use libraries (like jQuery), which provide DOM wrapper that works in all browsers. by Martin Kruliš (v1.1)

9 Document Object Model Node Traversing Node.firstChild, Node.lastChild
Node.childNodes Node.nextSibling, Node.previousSibling Node.parentNode, Node.parentElement Node.nodeName, Node.nodeValue Node.attributes – relevant for elements only Document.documentElement – root element Document.getElementsByTagName(tagName) Document.getElementById(id) by Martin Kruliš (v1.1)

10 Document Object Model Content Manipulation Extra Features
Document.createElement(), … Node.appendChild(), Node.insertBefore() Node.replaceChild(), Node.removeChild() Element.getAttribute(), Element.setAttribute() Element.removeAttribute() Node.cloneNode(deep) Extra Features Node.innerHTML, Node.outerHTML Document.evaluate(xpath) Example 1 by Martin Kruliš (v1.1)

11 DOM and CSS Cascading Style Sheets HTMLElement.style
Represent properties in style attribute Properties are represented in CSS object model var hln = document.getElementById("headline"); hln.style.backgroundColor = '#ffeecc'; Property names in model corresponds to names in CSS Dashes are removed and following words are capitalized Element.className, Element.classList Document.styleSheets[].cssRules[] .selectorText – string with CSS selector .style – same as Element.style Example 2 Note that style sheets can be modified (either editing style property of existing rule, or using insertRule() and deleteRule() methods). by Martin Kruliš (v1.1)

12 Events Event Model Top-level scripts are executed immediately
Other code can be attached to various events One event loop processed in single thread If the event is not processed, 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 … by Martin Kruliš (v1.1)

13 Events Event Handling Events may be handled by callback functions
Attached directly in HTML <button onclick="js code handling the event"> Or by Javascript code myButton.onclick = function(event) { ... } or myButton.addEventListener('click', fnc, capture); Todays choice – addEventListener() Allows multiple handlers on one event Works on any DOM element (not just visual elements) Allows early event capturing by Martin Kruliš (v1.1)

14 Events Event Object Event is represented by an object implementing Event interface Special events may implement some other interface derived from Event (e.g., MouseEvent) The object carries event information Event.target, Event.currentTarget Event.bubbles, Event.cancelable Event specific information (e.g., mouse coordinates) The event propagation may be disrupted Event.preventDefault() Event.stopPropagation() Event.preventDefault() – prevents default action of the browser (e.g., click on a submit button will not trigger submit of the form) Event.stopPropagation() – stops propagation of the event further (bubbling up) Event. Examples 3,4 by Martin Kruliš (v1.1)

15 Window Window Functions User interaction Important events Timers
window.alert(msg), window.confirm(msg) window.prompt(msg, defaultText) Important events window.onload window.onresize window.onbeforeunload, window.onunload Timers window.setTimeout(code, ms) window.setInterval(code, ms) window.clearTimeout(), window.clearInterval() by Martin Kruliš (v1.1)

16 Window Location History Read/write value gets/sets URL in address bar
location.host, location.pathname, … location.assign(url), location.replace(url) location.reload() History Manipulate the browser history of navigation history.length – number of items in history history.back(), history.forward() history.go(offset) – move in history by offset by Martin Kruliš (v1.1)

17 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 and provide callbacks Both GET and POST requests are supported 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.1)

18 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 Example 5 by Martin Kruliš (v1.1)

19 Cross-site Scripting Problem
... 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.1)

20 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.1)

21 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.1)

22 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.1)

23 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); 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. by Martin Kruliš (v1.1)

24 JavaScript and HTML5 HTML5 Non-visible Data Attributes
Standardizes and extends existing APIs Window, Location, History, … Add many new elements and features 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.1)

25 JavaScript and HTML5 History Multi-media and Graphics Elements
New feature – script state (history.state) history.pushState(), history.replaceState() Captures hidden script-managed state Allows backward/forward navigation over the states Multi-media and Graphics Elements Especially the <canvas> element 2D API for drawing Optional API for 3D graphic rendering (WebGL) Controlling multimedia Elements <audio> and <video> by Martin Kruliš (v1.1)

26 JavaScript and HTML5 Other New APIs Form validation
Abstraction for commands (actions) Application cache for offline working modes Custom protocol and media content handlers Editable and draggable (drag & drop) content Micro-data support Cross-document messaging, channel messaging Background (parallel) workers XMLHttpRequest Level 2, WebSockets WebGL, WebCL by Martin Kruliš (v1.1)

27 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 } JavaScript Libraries Solve the compatibility for you … jQuery, Dojo, MooTools, Prototype, … Examples Example – to compare features of various browsers see List of some intriguing JavaScript libraries can be found here or here by Martin Kruliš (v1.1)

28 jQuery jQuery JavaScript Library
Lightweight, feature rich, cross browser Also supports mobile platforms Philosophy – select and do Powerful selectors for DOM nodes Collective methods operating on DOM sets Features DOM manipulation (HTML and CSS) Event handling, integrated support for animations AJAX and related data handling by Martin Kruliš (v1.1)

29 jQuery Selectors Basic Methods CSS-like selectors for DOM nodes
$("selector") – returns jQuery wrapper for node set E.g., "element", ".class", "#id", "*", … Basic Methods DOM manipulation append(), remove(), html(), text(), … CSS manipulation and animated modifications css(), addClass(), removeClass(), hasClass(), … hide(), show(), animate(), … by Martin Kruliš (v1.1)

30 jQuery AJAX Related Libraries jQuery UI – user interface widgets
jQuery.ajax(url, { type:"GET", dataType:"text" }) .done(function(data) { code that process data }); jQuery.get(), jQuery.getJSON(), jQuery.post() Related Libraries jQuery UI – user interface widgets jQuery mobile QUnit – a unit testing framework by Martin Kruliš (v1.1)

31 Discussion by Martin Kruliš (v1.1)


Download ppt "Client-side Scripting"

Similar presentations


Ads by Google