-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
93 lines (85 loc) · 2.67 KB
/
content.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
const popup = document.createElement("div");
popup.style.cssText = `
position: absolute;
z-index: 9999;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
max-width: 400px;
padding: 16px;
text-align: center;
display: none; /* hide the popup by default */
`;
const title = document.createElement("h2");
title.style.cssText = `
color: #333;
font-size: 18px;
font-weight: bold;
margin-bottom: 8px;
`;
const thumbnail = document.createElement("img");
thumbnail.style.cssText = `
max-width: 80%;
margin-bottom: 16px;
`;
const summary = document.createElement("p");
summary.style.cssText = `
color: #666;
`;
const readMoreLink = document.createElement("a");
readMoreLink.style.cssText = `
color: #0072c6;
display: block;
margin-top: 16px;
`;
popup.appendChild(title);
popup.appendChild(thumbnail);
popup.appendChild(summary);
popup.appendChild(readMoreLink);
document.body.appendChild(popup); /* add the popup to the document */
document.addEventListener("mouseover", (e) => {
if (
e.target.tagName === "A" &&
e.target.href.startsWith("https://en.wikipedia.org/wiki/") &&
!popup.contains(e.target) /* check if the link is not inside the popup */
) {
const pageTitle = e.target.href.split("/").slice(-1)[0];
fetch(`https://en.wikipedia.org/api/rest_v1/page/summary/${pageTitle}`)
.then((response) => response.json())
.then((data) => {
title.innerText = data.title;
summary.innerText = data.extract;
thumbnail.src =
data.thumbnail?.source; /* use optional chaining to handle case where thumbnail is not provided */
thumbnail.alt = data.title;
readMoreLink.innerText = "Read more on Wikipedia";
readMoreLink.href = data.content_urls.desktop.page;
popup.style.top = `${e.pageY}px`;
popup.style.left = `${e.pageX}px`;
popup.style.display = "block"; /* show the popup */
})
.catch((error) => {
console.error(error);
});
}
});
popup.addEventListener("mouseleave", (e) => {
popup.style.display = "none"; /* hide the popup when the mouse leaves it */
});
document.addEventListener("mousemove", (e) => {
if (
popup.style.display === "block" /* only move the popup if it's visible */ &&
e.target.tagName !== "DIV" /* ignore mousemove events over the popup */ &&
e.target.tagName !== "H2" &&
e.target.tagName !== "P" &&
e.target.tagName !== "A" &&
e.target.tagName !== "IMG"
) {
popup.style.top = `${e.pageY}px`;
popup.style.left = `${e.pageX}px`;
}
});