Clientside Scripting Martin Kruli by Martin Kruli v

  • Slides: 31
Download presentation
Client-side Scripting Martin Kruliš by Martin Kruliš (v 1. 0) 24. 10. 2020 1

Client-side Scripting Martin Kruliš by Martin Kruliš (v 1. 0) 24. 10. 2020 1

Client-side Scripting � Including Scripts into Web Pages ◦ Dynamic modifications of HTML and

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. 0) 24. 10. 2020 2

Client-side Scripting � Application Examples ◦ Improving esthetic experience of the presentation (beyond CSS

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 canvas element) ◦ … Examples � Technologies ◦ Java. Script – on the rise, especially with HTML 5 ◦ VBScript – rarely used on web at present ◦ 3 rd party technologies (Flash, Silverlight, …) by Martin Kruliš (v 1. 0) 24. 10. 2020 3

Java. Script in HTML � Embedded Scripts <script type="text/javascript"> the Java. Script code The

Java. Script in HTML � Embedded Scripts <script type="text/javascript"> the Java. Script code The script must comply </script> to 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. 0) 24. 10. 2020 4

Java. Script in Web Browser � Browser Environment ◦ Global object window �API for

Java. Script in Web Browser � Browser Environment ◦ Global object window �API for current browser window �Presents the global context �Encapsulates all prepared objects �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. 0) 24. 10. 2020 5

Accessing Document � Document Object Model <html> <body> <h 1>DOM Example</h 1> <p> Document

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. 0) 24. 10. 2020 6

Accessing Document � Document Object Model ◦ Object model representing HTML/XML tree ◦ Class

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. 0) … Comment 24. 10. 2020 7

Accessing Document � DOM Level ◦ Incremental standards for DOM issued by W 3

Accessing Document � DOM Level ◦ Incremental standards for DOM issued by W 3 C ◦ Level 0 ◦ ◦ ◦ �Various technologies before standardization 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. 0) 24. 10. 2020 8

Document Object Model � Node ◦ ◦ ◦ ◦ ◦ Traversing Node. first. Child,

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. 0) 24. 10. 2020 9

Document Object Model � Content ◦ ◦ ◦ Manipulation Document. create. Element(), … Node.

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. 0) Example 1 24. 10. 2020 10

DOM and CSS � Cascading Style Sheets Example 2 ◦ HTMLElement. style �Represent properties

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 – string with CSS selector �. style – same as Element. style by Martin Kruliš (v 1. 0) Read only 24. 10. 2020 11

Events � Event Model ◦ Top-level scripts are executed immediately ◦ Other code can

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. 0) DOM Tree 24. 10. 2020 12

Events � Event Handling ◦ Events may be handled by callback functions �Attached directly

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 HTML) �Allows early event capturing by Martin Kruliš (v 1. 0) 24. 10. 2020 13

Events � Event Object ◦ Event is represented by an object implementing Event interface

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. 0) 24. 10. 2020 14

Window � Window Functions ◦ User interaction �window. alert(msg), window. confirm(msg) �window. prompt(msg, default.

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. 0) 24. 10. 2020 15

Window � Location ◦ ◦ Read/write value gets/sets URL in address bar location. host,

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. 0) 24. 10. 2020 16

AJAX � Asynchronous Java. Script and XML ◦ A technique that combines three technologies

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. 0) 24. 10. 2020 17

AJAX � XMLHttp. Request Object var http. Req = new XMLHttp. Request(); http. Req.

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. 0) 24. 10. 2020 18

Cross-site Scripting Problem <script>. . . find session ID. . . send it over

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) 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. 0) 24. 10. 2020 19

Cross-site Scripting Problem � Cross-site Scripting ◦ User injects malicious Java. Script into regular

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 sanitized by Martin Kruliš (v 1. 0) 24. 10. 2020 20

JSON � Java. Script Object Notation (JSON) ◦ Lightweight interchange format for structured data

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. 0) 24. 10. 2020 21

JSON � JSON Example [ Ordered list { Number (int) "Student. Id": 42, "Name":

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. 0) 24. 10. 2020 22

JSON � Applications in Java. Script ◦ Mainly for transfer of Java. Script structures

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 (the current version) ◦ Serialization �var json. String = JSON. stringify(js. Object); by Martin Kruliš (v 1. 0) 24. 10. 2020 23

Java. Script and HTML 5 � HTML 5 ◦ Standardizes and extends existing APIs

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 – element. dataset. foo. Bar by Martin Kruliš (v 1. 0) 24. 10. 2020 24

Java. Script and HTML 5 � History ◦ New feature – script state (history.

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. 0) 24. 10. 2020 25

Java. Script and HTML 5 � Other ◦ ◦ ◦ ◦ ◦ New APIs

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. 0) 24. 10. 2020 26

Compatibility Issues � Coding with Multi-browser Support ◦ Browsers developers implement the web standards

Compatibility Issues � Coding with Multi-browser Support ◦ Browsers developers implement the web standards when they want and how they want �Especially if we aim for older versions as well ◦ 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. 0) 24. 10. 2020 27

j. Query � j. Query Java. Script Library ◦ Lightweight, feature rich, cross browser

j. Query � j. Query Java. Script Library ◦ Lightweight, feature rich, cross browser �v 1. 10 – with backwards compatibility �v 2. 0 – new version that drops support of MSIE 6/7/8 ◦ 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. 0) 24. 10. 2020 28

j. Query � Selectors ◦ CSS-like selectors for DOM nodes $("selector") – returns j.

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(), … Example 6 by Martin Kruliš (v 1. 0) 24. 10. 2020 29

j. Query � AJAX j. Query. ajax(url, { type: "GET", data. Type: "text" }).

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. 0) 24. 10. 2020 30

Discussion by Martin Kruliš (v 1. 0) 24. 10. 2020 31

Discussion by Martin Kruliš (v 1. 0) 24. 10. 2020 31