console.log("Hello World!", browser);
document.addEventListener('DOMContentLoaded', function() {
const shortenButton = document.getElementById('shortenButton');
const resultDiv = document.getElementById('result');
const historyDiv = document.getElementById('history');
// Cargar historial al iniciar
loadHistory();
shortenButton.addEventListener('click', function() {
console.log("Botón clickeado");
browser.tabs.query({active: true, currentWindow: true})
.then(tabs => {
console.log("Tabs encontrados:", tabs);
if (!tabs || tabs.length === 0) {
throw new Error("No se pudo encontrar la pestaña activa");
}
const currentUrl = tabs[0].url;
console.log("URL actual:", currentUrl);
return browser.runtime.sendNativeMessage("cc.waifus.ShortWaifus.Extension", currentUrl);
})
.then(response => {
console.log("Respuesta recibida:", response);
if (response && !response.startsWith("Error:")) {
navigator.clipboard.writeText(response)
.then(() => {
resultDiv.className = 'success';
resultDiv.innerHTML = `
URL acortada y copiada al portapapeles
${response}
`;
saveToHistory(response);
})
.catch(err => {
console.error("Error al copiar al portapapeles:", err);
resultDiv.className = 'success';
resultDiv.innerHTML = `
URL acortada (no se pudo copiar)
${response}
`;
saveToHistory(response);
});
} else {
resultDiv.className = '';
resultDiv.textContent = `Error: ${response}`;
resultDiv.style.color = 'red';
}
})
.catch(error => {
console.error("Error en el proceso:", error);
resultDiv.className = '';
resultDiv.textContent = "Error al acortar la URL: " + error.message;
resultDiv.style.color = 'red';
});
});
function saveToHistory(shortUrl) {
browser.tabs.query({active: true, currentWindow: true})
.then(tabs => {
const currentTab = tabs[0];
const historyItem = {
title: currentTab.title,
url: shortUrl,
timestamp: Date.now()
};
browser.storage.local.get('history')
.then(data => {
let history = data.history || [];
history.unshift(historyItem);
history = history.slice(0, 5);
return browser.storage.local.set({ history: history });
})
.then(() => {
loadHistory();
})
.catch(error => {
console.error("Error al guardar en historial:", error);
});
})
.catch(error => {
console.error("Error al obtener información de la pestaña:", error);
});
}
function loadHistory() {
browser.storage.local.get('history')
.then(data => {
const history = data.history || [];
historyDiv.innerHTML = '';
history.forEach(item => {
const historyItem = document.createElement('div');
historyItem.className = 'history-item';
const title = document.createElement('div');
title.className = 'title';
title.textContent = item.title;
const url = document.createElement('div');
url.className = 'url';
url.textContent = item.url;
historyItem.appendChild(title);
historyItem.appendChild(url);
historyDiv.appendChild(historyItem);
});
})
.catch(error => {
console.error("Error al cargar historial:", error);
});
}
});