-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
71 lines (63 loc) · 1.71 KB
/
index.ts
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
//Intercepts the push state function to detect if an url has changed
window.history.pushState = new Proxy(window.history.pushState, {
apply: (
target,
thisArg,
argArray: [data: any, title: string, url?: string | null | undefined]
) => {
locationChange(argArray[2] || "");
return target.apply(thisArg, argArray);
},
});
const insertInHTML = (path: string, tries: number = 0) => {
let timeout;
if (path.match("/shop/(.*)")) {
const element = document.querySelector(
"div.category-header > div.category__title"
);
if (tries > 3) {
if (timeout) {
clearTimeout(timeout);
}
return;
}
if (!element) {
timeout = setTimeout(() => insertInHTML(path, tries + 1), 3000);
}
if (element) {
if (document.getElementById("__snippet_seo_description")) {
document.getElementById("__snippet_seo_description")?.remove();
}
setTimeout(() => renderHTML(element), 500);
}
}
};
const locationChange = async (newUrl: string) => {
insertInHTML(newUrl);
};
window.addEventListener("popstate", () => {
insertInHTML(window.location.pathname);
});
window.addEventListener("load", () => {
insertInHTML(window.location.pathname);
});
const renderHTML = (element: Element) => {
const metaDesc: string | undefined | null = Array.from(
document.querySelectorAll('meta[property="og:description"]')
)
?.pop()
?.getAttribute("content");
if (metaDesc) {
const description = document.createElement("div");
description.setAttribute("id", "__snippet_seo_description");
description.innerHTML = `
<p>
${metaDesc}
<br/>
</p>
`;
element.appendChild(description);
} else {
return;
}
};