Download presentation
Presentation is loading. Please wait.
Published byLester Gilmore Modified over 8 years ago
1
Martin Kruliš 26. 11. 2015 by Martin Kruliš (v1.1)1
2
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 26. 11. 2015 by Martin Kruliš (v1.1)2
3
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 – on the rise, especially with HTML5 ◦ VBScript – used in MSIE in the past ◦ 3 rd party technologies (Flash, Silverlight, …) 26. 11. 2015 by Martin Kruliš (v1.1)3 Examples
4
Embedded Scripts the JavaScript code Linked Scripts Event handlers 26. 11. 2015 by Martin Kruliš (v1.1)4 The script must comply with HTML rules
5
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 26. 11. 2015 by Martin Kruliš (v1.1)5
6
Document Object Model DOM Example Document Object Model is an API …... 26. 11. 2015 by Martin Kruliš (v1.1)6 body h1 p p img Document src DOM Example Document Object Model … alt html …
7
Document Object Model ◦ Object model representing HTML/XML tree ◦ Class of each node corresponds with the node type ◦ Different nodes allow different methods 26. 11. 2015 by Martin Kruliš (v1.1)7 Node Comment Text Element Document Attr CharacterData …
8
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 26. 11. 2015 by Martin Kruliš (v1.1)8
9
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) 26. 11. 2015 by Martin Kruliš (v1.1)9
10
Content Manipulation ◦ 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) 26. 11. 2015 by Martin Kruliš (v1.1)10 Example 1
11
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 26. 11. 2015 by Martin Kruliš (v1.1)11 Example 2
12
Event Model ◦ Top-level scripts are executed immediately ◦ Other code can be attached to various events ◦ One event loop processed in single thread 26. 11. 2015 by Martin Kruliš (v1.1)12 Event Queue Mouse Moved User Clicked Loading Finished Window Resized Dispatcher DOM Tree Target Processes one event at a time Target element is found … If the event is not processed, it bubbles up
13
Event Handling ◦ Events may be handled by callback functions Attached directly in HTML 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 26. 11. 2015 by Martin Kruliš (v1.1)13
14
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() 26. 11. 2015 by Martin Kruliš (v1.1)14 Examples 3,4
15
Window Functions ◦ User interaction 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() 26. 11. 2015 by Martin Kruliš (v1.1)15
16
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 ◦ history.back(), history.forward() ◦ history.go(offset) – move in history by offset 26. 11. 2015 by Martin Kruliš (v1.1)16
17
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) 26. 11. 2015 by Martin Kruliš (v1.1)17
18
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(); 26. 11. 2015 by Martin Kruliš (v1.1)18 Example 5
19
26. 11. 2015 by Martin Kruliš (v1.1)19 RegistrationAdmin Interface Name: Submit List of Users Kapslík... Fufník... find session ID...... send it over HTTP... Database Attacker’s Browser Malicious script gets executed in Admin’s web browser (i.e., in Admin’s context/session) Admin’s Browser
20
Cross-site Scripting ◦ User injects malicious JavaScript 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 26. 11. 2015 by Martin Kruliš (v1.1)20
21
JavaScript Object Notation (JSON) ◦ 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 26. 11. 2015 by Martin Kruliš (v1.1)21
22
JSON Example [ { "StudentId": 42, "Name": "John Smith" }, { "StudentId": 54, "Name": "Jane Johnson", "Graduated": true } ] 26. 11. 2015 by Martin Kruliš (v1.1)22 Ordered list Named collection Number (int) Unicode string Boolean literal
23
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); 26. 11. 2015 by Martin Kruliš (v1.1)23
24
HTML5 ◦ 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 26. 11. 2015 by Martin Kruliš (v1.1)24
25
History ◦ 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 element 2D API for drawing Optional API for 3D graphic rendering (WebGL) ◦ Controlling multimedia Elements and 26. 11. 2015 by Martin Kruliš (v1.1)25
26
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 26. 11. 2015 by Martin Kruliš (v1.1)26
27
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, … 26. 11. 2015 by Martin Kruliš (v1.1)27 Examples
28
jQuery JavaScript Library ◦ Lightweight, feature rich, cross browser v1.10 – with backwards compatibility v2.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 26. 11. 2015 by Martin Kruliš (v1.1)28
29
Selectors ◦ 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(), … 26. 11. 2015 by Martin Kruliš (v1.1)29
30
AJAX 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 26. 11. 2015 by Martin Kruliš (v1.1)30
31
26. 11. 2015 by Martin Kruliš (v1.1)31
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.