Clientside Scripting Martin Kruli by Martin Kruli v
Client-side Scripting Martin Kruliš by Martin Kruliš (v 1. 1) 07. 11. 2016 1
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š (v 1. 1) 07. 11. 2016 2
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) ◦ … Examples � Technologies ◦ Java. Script – dominating in current web applications ◦ VBScript – used in MSIE in the past ◦ 3 rd party technologies (Flash, Silverlight, …) by Martin Kruliš (v 1. 1) 07. 11. 2016 3
Java. Script in HTML � Embedded Scripts <script type="text/javascript"> the Java. Script code The script must comply </script> with HTML rules � Linked Scripts <script type="text/javascript" src="url"></script> � Event handlers <img src="url" onmouseover="code-handling-event"> by Martin Kruliš (v 1. 1) 07. 11. 2016 4
Java. Script 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š (v 1. 1) 07. 11. 2016 5
Accessing Document � Document Object Model <html> <body> <h 1>DOM Example</h 1> <p> Document Object Model is an API … h 1 </p> <img src="url" alt="text">. . . </body> DOM Example </html> html body … p img src alt Document Object Model … by Martin Kruliš (v 1. 1) 07. 11. 2016 6
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 Document Element Attr Character. Data Text by Martin Kruliš (v 1. 1) … Comment 07. 11. 2016 7
Accessing Document � DOM Level ◦ Incremental standards for DOM issued by W 3 C ◦ 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 by Martin Kruliš (v 1. 1) 07. 11. 2016 8
Document Object Model � Node ◦ ◦ ◦ ◦ ◦ Traversing Node. first. Child, Node. last. Child Node. child. Nodes Node. next. Sibling, Node. previous. Sibling Node. parent. Node, Node. parent. Element Node. node. Name, Node. node. Value Node. attributes – relevant for elements only Document. document. Element – root element Document. get. Elements. By. Tag. Name(tag. Name) Document. get. Element. By. Id(id) by Martin Kruliš (v 1. 1) 07. 11. 2016 9
Document Object Model � Content ◦ ◦ ◦ Manipulation Document. create. Element(), … Node. append. Child(), Node. insert. Before() Node. replace. Child(), Node. remove. Child() Element. get. Attribute(), Element. set. Attribute() Element. remove. Attribute() Node. clone. Node(deep) � Extra Features ◦ Node. inner. HTML, Node. outer. HTML ◦ Document. evaluate(xpath) by Martin Kruliš (v 1. 1) Example 1 07. 11. 2016 10
DOM and CSS � Cascading Style Sheets Example 2 ◦ HTMLElement. style �Represent properties in style attribute �Properties are represented in CSS object model var hln = document. get. Element. By. Id("headline"); hln. style. background. Color = '#ffeecc'; �Property names in model corresponds to names in CSS �Dashes are removed and following words are capitalized ◦ Element. class. Name, Element. class. List ◦ Document. style. Sheets[]. css. Rules[] �. selector. Text – string with CSS selector �. style – same as Element. style by Martin Kruliš (v 1. 1) 07. 11. 2016 11
Events � Event Model ◦ Top-level scripts are executed immediately ◦ Other code can be attached to various events ◦ One event loop processed in single thread Mouse Moved User Clicked Loading Finished Processes one event at a time If the event is not processed, it bubbles up Event Queue Dispatcher Target Window Resized Target element is found … by Martin Kruliš (v 1. 1) DOM Tree 07. 11. 2016 12
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 my. Button. onclick = function(event) {. . . } or my. Button. add. Event. Listener('click', fnc, capture); ◦ Todays choice – add. Event. Listener() �Allows multiple handlers on one event �Works on any DOM element (not just visual elements) �Allows early event capturing by Martin Kruliš (v 1. 1) 07. 11. 2016 13
Events � Event Object ◦ Event is represented by an object implementing Event interface �Special events may implement some other interface derived from Event (e. g. , Mouse. Event) ◦ The object carries event information �Event. target, Event. current. Target �Event. bubbles, Event. cancelable �Event specific information (e. g. , mouse coordinates) ◦ The event propagation may be disrupted �Event. prevent. Default() �Event. stop. Propagation() Examples 3, 4 by Martin Kruliš (v 1. 1) 07. 11. 2016 14
Window � Window Functions ◦ User interaction �window. alert(msg), window. confirm(msg) �window. prompt(msg, default. Text) ◦ Important events �window. onload �window. onresize �window. onbeforeunload, window. onunload ◦ Timers �window. set. Timeout(code, ms) �window. set. Interval(code, ms) �window. clear. Timeout(), window. clear. Interval() by Martin Kruliš (v 1. 1) 07. 11. 2016 15
Window � Location ◦ ◦ 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. back(), history. forward() history. go(offset) – move in history by offset by Martin Kruliš (v 1. 1) 07. 11. 2016 16
AJAX � Asynchronous Java. Script and XML ◦ A technique that combines three technologies �Java. Script �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š (v 1. 1) 07. 11. 2016 17
AJAX � XMLHttp. Request Object var http. Req = new XMLHttp. Request(); http. Req. open("GET", "index. php? ajax=1", true); http. Req. onreadystatechange = function() { if (http. Req. ready. State != 4) return; if (http. Req. status == 200) process. Response(http. Req. response. Text); else handle. Error(http. Req. status); } http. Req. send(); Example 5 by Martin Kruliš (v 1. 1) 07. 11. 2016 18
Cross-site Scripting Problem <script>. . . 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 Submit <script>. . . </> Fufník Database by Martin Kruliš (v 1. 1) 07. 11. 2016 19
Cross-site Scripting Problem � Cross-site Scripting ◦ User injects malicious Java. Script into regular data fields (registration form, e-mail 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š (v 1. 1) 07. 11. 2016 20
JSON � Java. Script Object Notation (JSON) ◦ Lightweight interchange format for structured data ◦ Based on subset of Java. Script 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š (v 1. 1) 07. 11. 2016 21
JSON � JSON Example [ Ordered list { Number (int) "Student. Id": 42, "Name": "John Smith" }, { } Unicode string Named collection "Student. Id": 54, "Name": "Jane Johnson", "Graduated": true Boolean literal ] by Martin Kruliš (v 1. 1) 07. 11. 2016 22
JSON � Applications in Java. Script ◦ Mainly for transfer of Java. Script structures �AJAJ – Asynchronous Java. Script and JSON ◦ Parsing �var res = eval(json. String); �Fast but not safe (the string may contain malicious code) �var res = JSON. parse(json. String); �JSON object was originally implemented in library and later added to ECMAScript 5 standard ◦ Serialization �var json. String = JSON. stringify(js. Object); by Martin Kruliš (v 1. 1) 07. 11. 2016 23
Java. Script and HTML 5 � HTML 5 ◦ 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. foo. Bar by Martin Kruliš (v 1. 1) 07. 11. 2016 24
Java. Script and HTML 5 � History ◦ New feature – script state (history. state) �history. push. State(), history. replace. State() �Captures hidden script-managed state �Allows backward/forward navigation over the states � Multi-media and Graphics Elements ◦ Especially the <canvas> element � 2 D API for drawing �Optional API for 3 D graphic rendering (Web. GL) ◦ Controlling multimedia �Elements <audio> and <video> by Martin Kruliš (v 1. 1) 07. 11. 2016 25
Java. Script and HTML 5 � 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 XMLHttp. Request Level 2, Web. Sockets Web. GL, Web. CL by Martin Kruliš (v 1. 1) 07. 11. 2016 26
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 ("XMLHttp. Request" in window) { AJAX code } else { no AJAX } � Java. Script Examples Libraries ◦ Solve the compatibility for you … ◦ j. Query, Dojo, Moo. Tools, Prototype, … by Martin Kruliš (v 1. 1) 07. 11. 2016 27
j. Query � j. Query Java. Script 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š (v 1. 1) 07. 11. 2016 28
j. Query � Selectors ◦ CSS-like selectors for DOM nodes $("selector") – returns j. Query wrapper for node set �E. g. , "element", ". class", "#id", "*", … � Basic Methods ◦ DOM manipulation �append(), remove(), html(), text(), … ◦ CSS manipulation and animated modifications �css(), add. Class(), remove. Class(), has. Class(), … �hide(), show(), animate(), … by Martin Kruliš (v 1. 1) 07. 11. 2016 29
j. Query � AJAX j. Query. ajax(url, { type: "GET", data. Type: "text" }). done(function(data) { code that process data }); ◦ j. Query. get(), j. Query. get. JSON(), j. Query. post() � Related Libraries ◦ j. Query UI – user interface widgets ◦ j. Query mobile ◦ QUnit – a unit testing framework by Martin Kruliš (v 1. 1) 07. 11. 2016 30
Discussion by Martin Kruliš (v 1. 1) 07. 11. 2016 31
- Slides: 31