Advanced Programming of Web Applications with Browser APIs

undefined
Browser APIs
N
S
W
I
1
5
3
 
-
 
A
d
v
a
n
c
e
d
 
P
r
o
g
r
a
m
m
i
n
g
 
o
f
 
W
e
b
 
A
p
p
l
i
c
a
t
i
o
n
s
 
2
0
2
3
/
2
0
2
4
P
e
t
r
 
Š
k
o
d
a
h
t
t
p
s
:
/
/
g
i
t
h
u
b
.
c
o
m
/
s
k
o
d
a
p
e
t
r
h
t
t
p
s
:
/
/
w
w
w
.
k
s
i
.
m
f
f
.
c
u
n
i
.
c
z
Showcase
HTML5TEST
html5test.com
 (dead)
html5test.co
Navigation
Location
 Object
Parsed URL (host, pathname, hash, .. )
assign(…), reload(…), replace(…)
Window Object
open
(url, target, windowFeatures)
onload
onbeforeunload
onunload
location
3
document.location === window.location
addEventListener(load', event => { });
window.onload = event => { };
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
History object
back(…), forward(…), go(…), …
pushState
(state, unused, url)
repalceState
(stateObj, unused, url)
state
Window Object
history
onpopstate
4
Web pages
Visibility API
Document.
visibilityState
Document.
onvisibilitychange
Scrolling:
Element.
scrollIntoView
(…)
Element.
scrollTo
(…)
Element.
scrollBy
(..,)
5
Multiple windows/tabs
State
Session-specific state
Application-wide intermediate state
Application-wide persisted state
Window Messaging
Window.
onmessage
Window.
postMessage
(…)
structuredClone
()
6
Mouse and pointer
Capturing Mouse Movement
Special cases of dragging mouse gesture
Continuous delivery of mouse events
Element.
setCaputure
(…)
Deprecated
: This feature is no longer
recommended
Element.
setPointerCapture
(…)
Element.
releasePointerCapture
(…)
Locking the Mouse Pointer
The pointer gets locked within one element
The cursor is hidden
Element. 
requestPointerLock
(…)
Experimental
Document.
exitPointerLock
(…)
Screen
Element.
requestFullscreen
(…)
7
Text
Text 
Selection
Operate on ranges
rangeCount, getRangeAt(…),
addRange(…), removeRange(…),
removeAllRanges()
Document.
getSelection
()
Start : anchorNode, anchorOffset
End: focusNode, focusOffset
Clipboard
Navigator.clipboard
Promised base API
Permission "clipboard-read"
Clipboard.
read
(…)
Clipboard.
readText
(…)
Clipboard.
write
(…)
Clipboard.
writeText
(…)
Document.
execCommand
()
Deprecated
8
Showcase
Code editor
CodeMirror
Ace
Portable devices
Screen Orientation
Screen
.
orientation
type, angle, onchange, …
Ambient Light
AmbientLightSensor
Vibration
Navigator.
vibrate
(…)
[100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100]
10
Geolocation
The best means available
Public IP geolocation information
WiFi networks in the vicinity and their signal
strengths
GSM/CDMA cell identifiers
Embedded GPS locator
Geolocation API
Navigator.
geolocation
Geolocation.
getCurrentPosition
(…)
TimeStamp, 
GeolocationCoordinates
Geolocation.
watchPosition
(…)
Geolocation.
clearWatch
(…)
11
Web notifications
Web 
Notifications API
Displayed outside the page at system level
Notification.
permission
Notification.
requestPermision
()
new 
Notification
(…)
12
new Notification(
  'To do list', {
    body: ‘Long notification text',
    icon: ‘./images/icon.png'
});
Multimedia
Animation Frames
Window.
requestAnimationFrame
(callback)
Window.
cancelAnimationFrame
(…)
Video
<video>
Accessibility concerns
Audio
<audio>
Web Audio API
13
<video controls width="250">
  <source
    src="/media/flower.webm"
    type="video/webm">
  <source
    src="/media/flower.mp4"
    type="video/mp4">
    Sorry, your browser doesn't support
embedded videos.
</video>
Canvas
HTML 5 element for JS drawing
Can be sized using CSS
with, height define resolution of the viewport
Canvas is cleared when resized.
Canvas context (2D, webGL)
14
<canvas
   id="mycanvas“
   width="640“
   height="480">
 Your browser does not support HTML5 canvas.
</canvas>
const context = mycanvas.getContext("2d");
Canvas 2D
Features:
Drawing rectangles, paths
Setting drawing styles
Color gradients, patterns
Text rendering
Linear transformations
Compositing, clipping paths
Context state stack
Retrieving/drawing image data, saving canvas as
image
Drawing images/video on canvas
Libraries:
PixiJS
Paper.js
Fabric.js
two.js
Easel.js
Graphics2D.js
Chart.js
15
 
OUT OF DATE
Canvas WebGL
Web API for OpenGL
Based on OpenGL ES 3.0 specification
'webgl' context
Libraries:
Three.js
16
var gl = canvas.getContext('webgl');
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
...
Web Cryptography
Encrypting/Decrypting data
Signing data (asymmetric decryption)
Hashing functions (integrity, security tokens, …)
Arsenal of mainstream algorithms
RSA, AES, SHA, …
Web Cryptography API
Crypto
CryptoKey
SubtleCrypto
encrypt
(algorithm, key, data)
decrypt
(…)
sign
(algorithm, key, data)
verify
(algorithm, key, signature, data)
digest
(algorithm, data)
17
WebSocket Protocol
Extension of HTTP(S) Protocols
Two-way communication
Persistent connections
Layered over TCP or SSL/TLS connection
Defined in detail in RFC 6455
Handshake is compatible with HTTP handshake
Simple message-based communication
User can specify custom sub-protocols
(i.e., the contents and semantics of the
messages)
18
WebSocket example
19
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
HTTP/1.1 101 
Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGz...
Sec-WebSocket-Protocol: chat
WebSocket Protocol FRAME
Data Frames
Message may be fragmented
Text message in UTF8
Binary messages are interpreted only by
the application
Control Frames
Close frame initiates graceful connection
shutdown
Ping/pong frames verify the connection
is still alive
20
Optional: 2023/2024
WebSocket API
WebSocket
 object:
constructor
(url, protocols)
send
(data)
close
(code, reason)
onopen
onmessage
onerror
onclose
21
// Create WebSocket connection.
const
 socket = new WebSocket('ws://localhost:8080');
// Listen for messages
socket.addEventListener('message', 
function
 (event) {
    console.log('Message from server ', event.data);
});
Takeaway
..
WebSocket
22
Slide Note
Embed
Share

Explore advanced programming techniques for web applications using Browser APIs like navigation, history, web pages visibility, multiple windows/tabs, mouse and pointer interaction, and text selection. Learn how to leverage these APIs to create dynamic and interactive web experiences.

  • Web Development
  • Browser APIs
  • Advanced Programming
  • Web Applications

Uploaded on Oct 01, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Browser APIs NSWI153 NSWI153 - - Advanced Advanced Programming of Web Applications Programming of Web Applications 202 2023/2024 3/2024 Petr Petr koda koda https://github.com/skodapetr https://github.com/skodapetr https://www.ksi.mff.cuni.cz https://www.ksi.mff.cuni.cz Creative Commons Attribution 4.0 International License This work is licensed under a Creative Commons Attribution 4.0 International License.

  2. Showcase HTML5TEST html5test.com (dead) html5test.co

  3. Navigation Location Object Window Object Parsed URL (host, pathname, hash, .. ) open(url, target, windowFeatures) assign( ), reload( ), replace( ) onload onbeforeunload onunload location document.location === window.location addEventListener(load', event => { }); window.onload = event => { }; 3

  4. History The Concept of History History object Inherited from original browsing concept. back( ), forward( ), go( ), The user reads a page, then browses on another page. pushState(state, unused, url) repalceState(stateObj, unused, url) Not entirely suitable for modern web applications. state State (view) of the application may change, yet the browser is still on the same page Window Object history onpopstate 4

  5. Web pages Visibility API Document.visibilityState Document.onvisibilitychange Scrolling: Element.scrollIntoView( ) Element.scrollTo( ) Element.scrollBy(..,) 5

  6. Multiple windows/tabs State Window Messaging Session-specific state Window.onmessage Application-wide intermediate state Window.postMessage( ) Application-wide persisted state structuredClone() 6

  7. Mouse and pointer Capturing Mouse Movement Locking the Mouse Pointer Special cases of dragging mouse gesture The pointer gets locked within one element Continuous delivery of mouse events The cursor is hidden Element.setCaputure( ) Deprecated: This feature is no longer recommended Element. requestPointerLock( ) Experimental Document.exitPointerLock( ) Element.setPointerCapture( ) Element.releasePointerCapture( ) Screen Element.requestFullscreen( ) 7

  8. Text Text Selection Clipboard Operate on ranges rangeCount, getRangeAt( ), addRange( ), removeRange( ), removeAllRanges() Navigator.clipboard Promised base API Permission "clipboard-read" Clipboard.read( ) Document.getSelection() Clipboard.readText( ) Start : anchorNode, anchorOffset Clipboard.write( ) End: focusNode, focusOffset Clipboard.writeText( ) Document.execCommand() Deprecated 8

  9. Showcase Code editor CodeMirror Ace

  10. Portable devices Screen Orientation Screen.orientation type, angle, onchange, Ambient Light AmbientLightSensor Vibration Navigator.vibrate( ) [100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100] 10

  11. Geolocation The best means available Geolocation API Public IP geolocation information Navigator.geolocation WiFi networks in the vicinity and their signal strengths Geolocation.getCurrentPosition( ) TimeStamp, GeolocationCoordinates GSM/CDMA cell identifiers Geolocation.watchPosition( ) Embedded GPS locator Geolocation.clearWatch( ) 11

  12. Web notifications Web Notifications API Displayed outside the page at system level Notification.permission Notification.requestPermision() new Notification( ) new Notification( 'To do list', { body: Long notification text', icon: ./images/icon.png' }); 12

  13. Multimedia Animation Frames Window.requestAnimationFrame(callback) <video controls width="250"> Window.cancelAnimationFrame( ) <source src="/media/flower.webm" type="video/webm"> Video <video> <source src="/media/flower.mp4" type="video/mp4"> Accessibility concerns Audio Sorry, your browser doesn't support embedded videos. <audio> Web Audio API </video> 13

  14. Canvas HTML 5 element for JS drawing Can be sized using CSS <canvas id="mycanvas width="640 height="480"> with, height define resolution of the viewport Canvas is cleared when resized. Canvas context (2D, webGL) Your browser does not support HTML5 canvas. </canvas> const context = mycanvas.getContext("2d"); 14

  15. Canvas 2D Features: Libraries: Drawing rectangles, paths PixiJS Setting drawing styles Paper.js Color gradients, patterns Fabric.js Text rendering two.js Linear transformations Easel.js Compositing, clipping paths Graphics2D.js Context state stack Chart.js Retrieving/drawing image data, saving canvas as image Drawing images/video on canvas 15

  16. Canvas WebGL Web API for OpenGL Libraries: Based on OpenGL ES 3.0 specification Three.js 'webgl' context var gl = canvas.getContext('webgl'); gl.viewport(0, 0, canvas.width, canvas.height); gl.clearColor(0.0, 0.0, 0.0, 1.0); ... 16

  17. Web Cryptography Encrypting/Decrypting data Web Cryptography API Signing data (asymmetric decryption) Crypto Hashing functions (integrity, security tokens, ) CryptoKey Arsenal of mainstream algorithms RSA, AES, SHA, SubtleCrypto encrypt(algorithm, key, data) decrypt( ) sign(algorithm, key, data) verify(algorithm, key, signature, data) digest(algorithm, data) 17

  18. WebSocket Protocol Extension of HTTP(S) Protocols User can specify custom sub-protocols (i.e., the contents and semantics of the messages) Two-way communication Persistent connections Layered over TCP or SSL/TLS connection Defined in detail in RFC 6455 Handshake is compatible with HTTP handshake Simple message-based communication 18

  19. WebSocket example GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGz... Sec-WebSocket-Protocol: chat 19

  20. WebSocket Protocol FRAME Data Frames 0 4 8 Mask 16 32 Message may be fragmented Length Extended Length (if length > 125) Ctrl. bits Op. Code Text message in UTF8 Extended Length (if length == 127) Binary messages are interpreted only by the application Extended Length (if length == 127) Masking Key (if mask == 1) Masking Key (continuation) Payload Data Control Frames Close frame initiates graceful connection shutdown Payload Data Ping/pong frames verify the connection is still alive Optional: 2023/2024 20

  21. WebSocket API WebSocket object: // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); constructor(url, protocols) send(data) // Listen for messages socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); close(code, reason) onopen onmessage onerror onclose 21

  22. Takeaway .. WebSocket 22

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#