-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path48.0_web_apis.js
138 lines (128 loc) · 4.4 KB
/
48.0_web_apis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
* ========================================================
* Web APIs - Part 1
* ========================================================
* Web APIs augment the capabilities of JavaScript, allowing developers to interact
* with the web browser or other hosting environments. Web APIs often provide a way
* to perform operations that aren't possible with JavaScript alone.
*/
/**
* ========================================================
* 1. XMLHttpRequest API
* ========================================================
* The traditional method for making HTTP requests in JavaScript.
* While it's mostly superseded by the Fetch API, it's still widely used in legacy codebases.
*/
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.send();
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.response);
} else {
console.log(`Error: ${xhr.status}`);
}
};
/**
* ========================================================
* 2. Fetch API
* ========================================================
* A modern way to fetch resources over the network. It returns Promises and
* is much cleaner and more powerful than XMLHttpRequest.
*/
fetch("https://api.example.com/data")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error("Fetch Error:", error));
/**
* ========================================================
* 3. Geolocation API
* ========================================================
* This API is used to get the geographic position of a user. Note that it requires user consent.
*/
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => console.error("Geolocation Error:", error)
);
/**
* ========================================================
* Nuances and Advanced Techniques
* ========================================================
*/
/**
* 1. AbortController for Fetch API
* --------------------------------
* The AbortController is used to terminate fetch requests.
* This can be helpful to abort requests based on certain conditions, like a timeout.
*/
const controller = new AbortController();
const { signal } = controller;
fetch("https://api.example.com/data", { signal })
.then((response) => response.json())
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
}
});
// To abort the fetch
controller.abort();
/**
* 2. Using the Cache API
* ----------------------
* This API allows you to cache network resources. This can significantly improve
* the performance of web applications by reducing load times.
*/
caches.open("my-cache").then((cache) => {
cache
.add("https://api.example.com/data")
.then(() => console.log("Data cached"))
.catch((error) => console.error("Cache Error:", error));
});
/**
* 3. Clipboard API
* ----------------
* The Clipboard API is used for interacting with the clipboard to read and write text.
*/
navigator.clipboard
.writeText("Copied text")
.then(() => console.log("Text copied to clipboard"))
.catch((err) => console.error("Clipboard Error:", err));
/**
* 4. Notification API
* -------------------
* Allows you to display native system notifications.
* This can enhance the user experience by providing real-time updates.
*/
if (Notification.permission === "granted") {
new Notification("Hello, world!");
} else {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("Hello, world!");
}
});
}
/**
* 5. Intersection Observer API
* ----------------------------
* Useful for detecting when an element enters or exits the viewport.
* Common use-cases include lazy-loading images and infinite scrolling.
*/
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// Perform action, such as lazy-loading an image
console.log("Element is in the viewport!");
}
});
});
// To observe a specific element
observer.observe(document.querySelector(".some-element"));