Martin Kruliš 26. 11. 2015 by Martin Kruliš (v1.1)1.
-
Upload
lester-gilmore -
Category
Documents
-
view
214 -
download
0
Transcript of Martin Kruliš 26. 11. 2015 by Martin Kruliš (v1.1)1.
by Martin Kruliš (v1.1) 1
Client-side Scripting
Martin Kruliš
26. 11. 2015
by Martin Kruliš (v1.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
Client-side Scripting
by Martin Kruliš (v1.1) 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◦ 3rd party technologies (Flash, Silverlight, …)
26. 11. 2015
Client-side Scripting
Examples
by Martin Kruliš (v1.1) 4
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">
26. 11. 2015
JavaScript in HTML
The script must comply with HTML rules
by Martin Kruliš (v1.1) 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
JavaScript in Web Browser
by Martin Kruliš (v1.1) 6
Document Object Model<html> <body> <h1>DOM Example</h1> <p> Document Object Model is an API … </p> <img src="url" alt="text"> ... </body></html>
26. 11. 2015
Accessing Document
body
h1 p img
Document
src
DOM Example Document Object Model
…
alt
html
…
by Martin Kruliš (v1.1) 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
Accessing Document
Node
CommentText
ElementDocument Attr CharacterData …
by Martin Kruliš (v1.1) 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
Accessing Document
by Martin Kruliš (v1.1) 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
Document Object Model
by Martin Kruliš (v1.1) 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
Document Object Model
Example 1
by Martin Kruliš (v1.1) 11
Cascading Style Sheets◦ HTMLElement.style
Represent properties in style attribute Properties are represented in CSS object modelvar 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
DOM and CSS
Example 2
by Martin Kruliš (v1.1) 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
Events
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
by Martin Kruliš (v1.1) 13
Event Handling◦ Events may be handled by callback functions
Attached directly in HTML<button onclick="js code handling the event">
Or by Javascript codemyButton.onclick = function(event) { ... }ormyButton.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
Events
by Martin Kruliš (v1.1) 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
Events
Examples 3,4
by Martin Kruliš (v1.1) 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
Window
by Martin Kruliš (v1.1) 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
Window
by Martin Kruliš (v1.1) 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
AJAX
by Martin Kruliš (v1.1) 18
XMLHttpRequest Objectvar 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
AJAX
Example 5
by Martin Kruliš (v1.1) 1926. 11. 2015
Cross-site Scripting Problem
Registration Admin Interface
Name:
Submit
List of Users
Kapslík
<script>...</>
Fufník
<script>... find session ID ...... send it over HTTP ...</script>
Database
Attacker’s Browser
Malicious script gets executed in Admin’s web browser (i.e., in Admin’s context/session)
Admin’s Browser
by Martin Kruliš (v1.1) 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
Cross-site Scripting Problem
by Martin Kruliš (v1.1) 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
JSON
by Martin Kruliš (v1.1) 22
JSON Example[ { "StudentId": 42, "Name": "John Smith" }, { "StudentId": 54, "Name": "Jane Johnson", "Graduated": true }]
26. 11. 2015
JSON
Ordered list
Named collection
Number (int)
Unicode string
Boolean literal
by Martin Kruliš (v1.1) 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
JSON
by Martin Kruliš (v1.1) 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
JavaScript and HTML5
by Martin Kruliš (v1.1) 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 <canvas> element
2D API for drawing Optional API for 3D graphic rendering (WebGL)
◦ Controlling multimedia Elements <audio> and <video>
26. 11. 2015
JavaScript and HTML5
by Martin Kruliš (v1.1) 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
JavaScript and HTML5
by Martin Kruliš (v1.1) 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/versionif ("XMLHttpRequest" in window) { AJAX code }else { no AJAX }
JavaScript Libraries◦ Solve the compatibility for you …◦ jQuery, Dojo, MooTools, Prototype, …
26. 11. 2015
Compatibility Issues
Examples
by Martin Kruliš (v1.1) 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
jQuery
by Martin Kruliš (v1.1) 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
jQuery
by Martin Kruliš (v1.1) 30
AJAXjQuery.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
jQuery
by Martin Kruliš (v1.1) 3126. 11. 2015
Discussion