Presentation is loading. Please wait.

Presentation is loading. Please wait.

UI-related HTML5 APIs Martin Kruliš

Similar presentations


Presentation on theme: "UI-related HTML5 APIs Martin Kruliš"— Presentation transcript:

1 UI-related HTML5 APIs Martin Kruliš
Please note that many of the presented technologies are still experimental and may not be supported in all web browsers. Check for compatibility references. by Martin Kruliš (v1.2)

2 Web Pages in Browser Web Page Context
Current browsers allow opening multiple windows or tabs (i.e., display multiple pages) Each page must have its own isolated context Some pages may not be visible (only 1 tab is selected) Page visibility API document.hidden document.visibilityState hidden, visible, prerender, unloaded document.onvisibilitychange event Scrolling control scrollIntoView(), scrollTo(), scrollBy() by Martin Kruliš (v1.2)

3 Embedded Web Pages Sandboxed <iframe>
The <iframe> element is used to create a nested browsing context within a page sandbox attribute activates extra restrictions Some of these restrictions may be lifted allow-forms (form submission) allow-modals (opening modal windows) allow-popups (opening windows) allow-scripts (run scripts) allow-top-navigation (navigate in parent context) by Martin Kruliš (v1.2)

4 Navigation Location Object Window Object and Navigation
document.location, window.location Contains parsed URL (host, pathname, hash, …) assign(), reload(), replace() Replace is not saved in history Window Object and Navigation window.open() window.onload window.onhashchange window.onbeforeunload, window.onunload URL hash change (either by hyperlink click or by modifying the location.hash value) does not lead to browsing (only onhashchange is triggered and possibly the page viewport is scrolled). by Martin Kruliš (v1.2)

5 Navigation History The Concept of History
Inherited from original browsing concept The user reads a page, then browses on another page Not entirely suitable for modern web applications State (view) of the application may change, yet the browser is still on the same page window.history API back(), forward(), go(), length pushState(data, title, [url]), replaceState(…) state window.onpopstate event The pushState/replaceState methods and onpopstate event can be used to alter the behavior of the Back/Forward buttons in the browser to navigate via application logical states. E.g., the Back/Forward buttons can emulate Undo/Redo buttons in an editor application. by Martin Kruliš (v1.2)

6 Web Messaging Cross Document Messaging
Relatively safe way how web applications opened in one browser can communicate The window object has onmessage event Event object holds information about the sending window, its origin, and message data The origin can be used to prevent undesirable cross- site data transfers A message can be sent to another window by targetWindow.sendMessage(msg, origin); Usually, this technology is used to control (exchange information with) child windows such as dialogs or iframes. Example 1 by Martin Kruliš (v1.2)

7 Web Notifications Web Notifications API
Notifications from a web page context which are displayed outside the page at system level New , calendar event, progress report, … Notifications must be permitted by the user Notification.permission default (not determined yet), granted, denied Notification.requestPermision() Returns Promise, which is given the decided permission Triggers a UI query, whether the notifications are permitted for this application by Martin Kruliš (v1.2)

8 Web Notifications Notification Object new Notification(title, options)
body – text of notification icon – URL of an icon image vibrate – vibration pattern noscreen – whether the screen should be activated silent – whether a sound/vibration should be played sound – URL to a sound file to be played onclick, onerror, onshow, onclose close() Example 2 by Martin Kruliš (v1.2)

9 Identifier is auto-converted to camelCase
Data Attributes Data in DOM Special data attributes data-* <a href="…" data-confirm-msg="Really go to…?"> Easily accessible by Javascript Using regular HTML5 API confirm(mylink.dataset.confirmMsg); mylink.dataset.clicked = true; Using jQuery wrapper $("a[data-confirm-msg]").click(function(e){ if (!confirm($(this).data("confirmMsg")) e.preventDefault(); }); Identifier is auto-converted to camelCase by Martin Kruliš (v1.2)

10 Callback gets a list of changes after they are completed
Mutation Observer Mutation Observer Designed to replace DOM mutation events Observes selected DOM nodes for changes and triggers a callback every time a change occurs var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { // handle the mutation }); observer.observe(targetNode, { attributes: true, childList: true, subtree: true, Callback gets a list of changes after they are completed The DOM mutation events were deprecated due to their performance issues. The MutationObserver is designed to provide similar functionality in a more efficient way. All the DOM modifications are performed first and then the observer’s callback is invoked with a list of changes. Monitor attribute changes, child node add/remove and do it recursively on the subtree by Martin Kruliš (v1.2)

11 Editable Content Editable Content
A way how to turn browser into WYSIWYG editor Selected element or the whole document becomes interactive and the user may change the contents For selected elements element.contentEditable (true, false, inherit) element.isContentEditable For the whole document document.designMode (on, off) Particularly useful for a page inside <iframe> by Martin Kruliš (v1.2)

12 Editable Content Using Commands when Editing Content
Commands modify the text selection, insert new contents, or change editing parameters document.execCommand(cmd, defautUI, value) Affects currently active (focused) editable element Additional support methods queryCommandSupported() queryCommandEnabled() queryCommandValue() queryCommandState() queryCommandIndeterm() execCommand() arguments command – name of te command as string defaultUI – whether to show default UI controls (currently not supported in Mozilla) valueArg – argument of the command (depends on the command type) QueryCommand… Value – returns value on current selection State – whether the command has been invoked on current selection Indeterm – whether a formatting command is in a indeterminate state on current selection by Martin Kruliš (v1.2)

13 Editable Content Editing Commands copy, cut, paste
delete, forwardDelete undo, redo insertText, insertParagraph, insertImage createLink bold, italic foreColor, backColor enableObjectResizing styleWithCSS Example 3 by Martin Kruliš (v1.2)

14 Text Selection API Text Selection document.selection
anchorNode, focusNode – begin/end DOM node Operate on ranges rangeCount, getRangeAt(idx) addRange(), removeRange(), removeAllRanges() Range is object representing continuous text startContainer, startOffset, endContainer, endOffset setStart(), setEnd(), … by Martin Kruliš (v1.2)

15 Clipboard Clipboard Events and API ClipboardEvent
Used in event handlers Can be constructed and triggered To emulate clipboard operations (e.g., when editing) Document events cut, copy, and paste Allows intercepting/modifying clipboard events navigator.clipboard read(), write() Asynchronous API (returns promise) Some restrictions may be applied by Martin Kruliš (v1.2)

16 Drag and Drop Drag-and-Drop Mouse Gesture HTML Attributes
Standard gesture for moving/copying items Strings (text, html, URLs, …) and files (binary data) Within browser, to browser, from browser Better support added with HTML5 HTML Attributes The draggable attribute Makes a HTML element drag-able <img draggable="true" src="…" alt="…"> The dropzone attribute Not well supported yet by Martin Kruliš (v1.2)

17 Drag and Drop Drag and Drop Events dragstart dragenter, dragleave
Fired on dragged element when the operation begins Usually fills the dataTransfer property dragenter, dragleave Fired on possible drop destinations dragover If valid, the preventDefault() should be called dragend Fired on dragged element when the operation finishes by Martin Kruliš (v1.2)

18 Drag and Drop Drag and Drop Events drop The dataTransfer property
Fired on destination element when the op. finishes Should process the transferred data The dataTransfer property dropEffect, effectAllowed Copy, move, link, … getData(), setData() items – container with transferred items files – a file list (if files are being dragged) The items container is currently not implemented in all browsers (e.g., it is missing in Firefox). Example 4 by Martin Kruliš (v1.2)

19 Mouse Capture Capturing Mouse Movement
Special cases of dragging mouse gesture Mouse capture provides continuous delivery of mouse events to target object Until the drag is released (button goes up) element.setCaputure() The element starts capturing the mouse movement Usually invoked in mousedown event document.releaseCapture() Releases any captures in the document by Martin Kruliš (v1.2)

20 Pointer Lock Locking the Mouse Pointer
The pointer gets locked within one element Pointer does not leave the element (nor is clamped) The cursor is hidden Persistent (until released) regardless buttons state API element.requestPointerLock() document.exitPointerLock() pointerlockchange, pointerlockerror element.requestFullscreen() Mouse events are extended with relative coordinates ev.movementX, ev.movementY Current implementations of pointer lock are bound to fullscreen mode. Furthermore, most of the functions and properties are currently prefixed (moz, webkit,…). by Martin Kruliš (v1.2)

21 Portable Devices Screen Orientation Device Orientation
screen.orientation – orientation object type – text string (enum) with current orientation angle – rotation angle in degrees onchange event lock(), unlock() Device Orientation Gathered values from the accelerometer The deviceorientation event of the window ev.alpha, ev.beta, ev.gamma – rotations in degrees by Martin Kruliš (v1.2)

22 Portable Devices Proximity Sensor
Detects, when an object (user) gets close to the device (e.g., when a phone is held by user’s ear) The deviceproximity event of the window ev.min, ev.max – detection range in centimeters ev.value – distance in centimeters The userproximity event of the window ev.near – bool flag, whether an object is very close by by Martin Kruliš (v1.2)

23 Portable Devices Ambient Light Vibration API
Notifies when the surrounding illumination changes The devicelight event of the window ev.value – illumination level in lux Vibration API Controls vibrations of a portable device navigator.vibrate(length) one number (duration in ms) array of numbers – duration of vibrations and pauses by Martin Kruliš (v1.2)

24 Geolocation Geolocation Motivation
Means to identify user’s position in the world The script receives latitude and longitude values Motivation Geographically specific search Looking for objects near the user’s location Annotating contents generated by user Selecting appropriate type of service for the user Selecting nearest server, optimal shipping of goods, … by Martin Kruliš (v1.2)

25 Geolocation How does it work? Server-side Client Geolocation
The standard defines only the API The platform uses the best means available, like Public IP geolocation information WiFi networks in the vicinity and their signal strengths GSM/CDMA cell identifiers Embedded GPS locator Server-side Client Geolocation From public IP only Can be used without browser support/cooperation Note that the browser should treat the location of the user as a strictly personal information and it should query the user whether the location may be revealed to the application. The server-side geolocation that uses the IP address of the client should be treated carefully. The information may be extremely inaccurate due to networking technologies like NAT or ISP internal network relays. by Martin Kruliš (v1.2)

26 Geolocation API Geolocation Interface Object
In navigator.geolocation attribute Simple test for presence if (!"geolocation" in navigator) { // Oops, we do not have the position... } Provides two basis functions One-shot request Repetitive position update notifications by Martin Kruliš (v1.2)

27 Geolocation API One-shot Request
getCurrentPosition(success [, error [, opts]]) The function initiates an asynchronous request for the geographic location (return immediately) success – function callback that fires when the location is established error – function callback fired in case of a failure opts – an object with options enableHighAccuracy timeout – how long to wait for the position (ms) maximumAge – how old positions from the cache the system can use (ms) by Martin Kruliš (v1.2)

28 Geolocation API Success Callback Error Callback
timestamp – DOMTimeStamp of the position coords – object with coordinates latitude, longitude – WGS in degrees accuracy – precision of the location in meters optionally altitude, altitudeAccuracy (meters) optionally heading (azimuth) and speed (kph) Error Callback code – indicates type of the error message – user-readable error message by Martin Kruliš (v1.2)

29 Geolocation API Watching Position Updates
watchPosition(success [, error [, opts]]) Yields watchId, identifier of the watch process Same parameters as getCurrentPosition Similar semantics, but success is called every time the position significantly changes Details are implementation specific clearWatch(watchId) Stops watching process and release resources Example 5 by Martin Kruliš (v1.2)

30 Discussion by Martin Kruliš (v1.2)


Download ppt "UI-related HTML5 APIs Martin Kruliš"

Similar presentations


Ads by Google