1 / 31

Client-side Scripting

Client-side Scripting. Martin Kruli š. 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

dharlow
Download Presentation

Client-side Scripting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  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.0)

  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 canvas element) • … • Technologies • JavaScript – on the rise, especially with HTML5 • VBScript – rarely used on web at present • 3rd party technologies (Flash, Silverlight, …) Examples by Martin Kruliš (v1.0)

  4. JavaScript in HTML • Embedded Scripts <script type="text/javascript"> the JavaScript code </script> • Linked Scripts <script type="text/javascript" src="url"></script> • Event handlers <imgsrc="url"onmouseover="code-handling-event"> The script must comply to HTML rules by Martin Kruliš (v1.0)

  5. JavaScript 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š (v1.0)

  6. Accessing Document Document • Document Object Model <html> <body> <h1>DOM Example</h1> <p> Document Object Model is an API … </p> <imgsrc="url" alt="text"> ... </body> </html> html body … h1 p img src alt Document Object Model … DOM Example by Martin Kruliš (v1.0)

  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 Document Element Attr CharacterData … Text Comment by Martin Kruliš (v1.0)

  8. Accessing Document • DOM Level • Incremental standards for DOM issued by W3C • 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š (v1.0)

  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.0)

  10. Document Object Model • 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) Example 1 by Martin Kruliš (v1.0)

  11. DOM and CSS • Cascading Style Sheets • HTMLElement.style • Represent properties in style attribute • Properties are represented in CSS object model varhln = 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[] • .selector – string with CSS selector • .style – same as Element.style Example 2 Read only by Martin Kruliš (v1.0)

  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 Processes one event at a time Mouse Moved User Clicked Event Queue Dispatcher Loading Finished Target Target element is found … Window Resized DOM Tree by Martin Kruliš (v1.0)

  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) { ... } ormyButton.addEventListener('click', fnc, capture); • Todays choice – addEventListener() • Allows multiple handlers on one event • Works on any DOM element (not just HTML) • Allows early event capturing by Martin Kruliš (v1.0)

  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() Examples 3,4 by Martin Kruliš (v1.0)

  15. Window • 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() by Martin Kruliš (v1.0)

  16. 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 • history.back(), history.forward() • history.go(offset) – move in history by offset by Martin Kruliš (v1.0)

  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.0)

  18. AJAX • XMLHttpRequest Object varhttpReq = newXMLHttpRequest(); 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(); Example 5 by Martin Kruliš (v1.0)

  19. Cross-site Scripting Problem Malicious script gets executed in Admin’s web browser (i.e., in Admin’s context) <script> ... find session ID ... ... send it over HTTP ... </script> Admin’s Browser Attacker’s Browser Registration Admin Interface List of Users Name: Submit Database by Martin Kruliš (v1.0)

  20. Cross-site Scripting Problem • 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 sanitized by Martin Kruliš (v1.0)

  21. JSON • 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 by Martin Kruliš (v1.0)

  22. JSON • JSON Example [ { "StudentId": 42, "Name": "John Smith" }, { "StudentId": 54, "Name": "Jane Johnson", "Graduated": true } ] Ordered list Number (int) Unicode string Named collection Boolean literal by Martin Kruliš (v1.0)

  23. JSON • Applications in JavaScript • Mainly for transfer of JavaScript structures • AJAJ – Asynchronous JavaScript and JSON • Parsing • varres = eval(jsonString); • Fast but not safe (the string may contain malicious code) • varres = JSON.parse(jsonString); • JSON object was originally implemented in library and later added to ECMAScript 5 standard (the current version) • Serialization • varjsonString = JSON.stringify(jsObject); by Martin Kruliš (v1.0)

  24. JavaScript and HTML5 • 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 – element.dataset.fooBar by Martin Kruliš (v1.0)

  25. JavaScript and HTML5 • 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> by Martin Kruliš (v1.0)

  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.0)

  27. 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 ("XMLHttpRequest" inwindow) { AJAX code } else { no AJAX } • JavaScript Libraries • Solve the compatibility for you … • jQuery, Dojo, MooTools, Prototype, … Examples by Martin Kruliš (v1.0)

  28. jQuery • 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 by Martin Kruliš (v1.0)

  29. jQuery • 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(), … Example 6 by Martin Kruliš (v1.0)

  30. jQuery • 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 by Martin Kruliš (v1.0)

  31. Discussion by Martin Kruliš (v1.0)

More Related