url-shortener/data/www/app.js

80 lines
1.9 KiB
JavaScript

const url = document.getElementById('url');
const copy_link = document.getElementById('copy_link');
const outls = document.getElementById('outls');
const shorten_btn = document.getElementById('shorten_btn');
copy_link.onclick = ()=>{
navigator.clipboard.writeText(url.value);
};
function add_url_to_table({url,shorten,created})
{
/*<tr>
<td class="mdl-data-table__cell--non-numeric" */
const tr= document.createElement('tr');
const urltd = document.createElement('td');
urltd.classList.add('mdl-data-table__cell--non-numeric');
const urla = document.createElement('a');
urla.href = url;
urla.innerText = url;
urltd.appendChild(urla);
const shortentd = document.createElement('td');
const shortena = document.createElement('a');
shortena.href = shorten;
shortena.innerText = shorten;
shortentd.appendChild(shortena);
const createdtd = document.createElement('td');
createdtd.innerText = created;
tr.appendChild(urltd);
tr.appendChild(shortentd);
tr.appendChild(createdtd);
outls.prepend(tr);
}
function getIds()
{
var ids= localStorage.getItem('ids');
if(ids === null)
{
return [];
}
else
{
return JSON.parse(ids);
}
}
async function add_url()
{
var formData = new FormData();
formData.set('url',url.value);
var fetchD= await fetch("./api/v1/AddEntry",{method: 'post', body: formData});
var jsonData = await fetchD.json();
if(jsonData.Success)
{
var item = {
url: url.value,
shorten: jsonData.Url,
created: jsonData.Created
};
var ids=getIds();
ids.push(item);
localStorage.setItem('ids',JSON.stringify(ids));
add_url_to_table(ids);
url.value = jsonData.Url;
}
else
{
//fail
}
}
getIds().forEach(element => {
add_url_to_table(element);
});
shorten_btn.onclick = function(){
add_url();
}