-
Notifications
You must be signed in to change notification settings - Fork 30
/
browser.js
97 lines (79 loc) · 2.49 KB
/
browser.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
// Change this to "true" if you are developing locally
const isDev = "false";
// Query the elements we need from the DOM
const form = document.querySelector("form");
const urlInput = document.querySelector("[data-url-input]");
const imageHolder = document.querySelector("[data-image-holder]");
const imageHolderTitle = document.querySelector("[data-image-holder-title]");
const loader = document.querySelector("[data-loader]");
const error = document.querySelector("[data-error]");
function buildImageElement(url) {
const imageEl = document.createElement("img");
imageEl.setAttribute("src", url);
imageEl.setAttribute("id", "generatedImage");
return imageEl;
}
function clearImageHolder() {
const imageEl = document.getElementById("generatedImage");
if (imageEl) {
imageHolderTitle.style.display = "none";
imageEl.remove();
}
}
function showLoader() {
loader.style.display = "block";
}
function hideLoader() {
loader.style.display = "none";
}
function showError() {
error.style.display = "block";
}
function hideError() {
error.style.display = "none";
}
// Get a possible page param to prefill the urlInput field
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("page")) {
urlInput.value = urlParams.get("page");
}
// Call out to the serverless function on form submit
form.addEventListener("submit", async (event) => {
// prevent usual HTML form submit
event.preventDefault();
hideError();
// update the page url param to reflect the form submission
const newUrlParams = new URLSearchParams(window.location.search);
newUrlParams.set("page", urlInput.value);
// update the push state so we can navigate back / forwards between
// different URLs
window.history.pushState(
{},
"",
`${window.location.pathname}?${decodeURIComponent(newUrlParams)}`
);
clearImageHolder();
showLoader();
try {
await fetch(`/api/screenshot?page=${urlInput.value}&isDev=${isDev}`)
.then((response) => {
if (response.status === 500) {
hideLoader();
showError();
return;
}
return response.blob();
})
.then((blob) => {
const url = URL.createObjectURL(blob);
// build up the image element with the url
const newImageEl = buildImageElement(url);
imageHolderTitle.style.display = "block";
// add the new element to the DOM
imageHolder.appendChild(newImageEl);
hideLoader();
});
} catch (error) {
showError();
}
});