linkylinky-chrome/main.js

86 lines
3.0 KiB
JavaScript

//Clipboard stuff
const baseurl = "https://kauft.es";
const btn = document.getElementById("shorturl_copy");
const clipboard = new ClipboardJS(btn);
clipboard.on('success', function (e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
new Notification('Copied Shorturl', {
icon: 'https://git.odit.services/user/avatar/kauft.es/140',
body: `Copied the shorturl to your clipboard: ${e.text}`,
});
});
//Set default url
// chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
// document.getElementById("target").value = tabs[0].url;
// });
document.getElementById("target").value = "google.com";
// Calls the api to create a new short url
document.getElementById("create").onclick = createUrl;
function createUrl() {
let shorturl = {
target: document.getElementById("target").value,
shortcode: document.getElementById("shortcode").value
};
if (shorturl.shortcode == "" | !shorturl.shortcode) {
delete shorturl.shortcode;
}
fetch(`${baseurl}/api`, {
method: "POST",
body: JSON.stringify(shorturl),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => {
if (!res.ok) {
handleError(res);
}
else {
res.json()
}
})
.then(res => {
document.getElementById("shorturl").innerText = res.url;
document.getElementById("shorturl_container").className = "";
document.getElementById("target_container").className = "hidden";
document.getElementById("shortcode_container").className = "hidden";
document.getElementById("create").classList.add("hidden");
document.getElementById("reset").classList.remove("hidden");
});
}
document.getElementById("error_dismiss").onclick = () =>{
document.getElementById("error_container").classList.add("hidden");
};
/**
* Display alerts for errors (only handling 400 correctly r/n)
* @param {response} res The fetch response object
*/
function handleError(res) {
if (res.status == 400) {
res.text().then((body)=>{
document.getElementById("error_text").innerText=body;
document.getElementById("error_container").classList.remove("hidden");
})
}
}
//Resets the UI
document.getElementById("reset").onclick = reset;
function reset() {
document.getElementById("shorturl").innerText = "";
document.getElementById("target_container").className = "";
document.getElementById("shortcode_container").className = "";
document.getElementById("shorturl_container").className = "hidden";
document.getElementById("reset").classList.add("hidden");
document.getElementById("create").classList.remove("hidden");
chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
document.getElementById("target").value = tabs[0].url;
});
}