tabsaver/popup.js
2025-05-18 21:43:52 +02:00

77 lines
2.0 KiB
JavaScript
Executable File

let currentWindow;
chrome.windows.getCurrent((_window) => {
currentWindow = _window;
});
let saveButton = document.querySelector("div.link.save");
let restoreButton = document.querySelector("div.link.restore");
window.addEventListener("keydown", (event) => {
switch (event.key) {
case "s":
case "S":
saveButton.click();
break;
case "r":
case "R":
restoreButton.click();
break;
case "Escape":
window.close();
break;
}
});
async function save(event) {
event.preventDefault();
event.stopImmediatePropagation();
let content = "";
// iterate ghrough all windows and all tabs
// windows are separated by a blank line
// tabs are separated by newline
const _windows = await chrome.windows.getAll({ populate: true });
_windows.forEach((_window, _windowIndex) => {
// ignore this popup window
if (_window.id == currentWindow.id) return;
_window.tabs.forEach((_tab, _tabIndex) => {
content += _tab.url + "\n";
});
content += "\n";
});
const fileHandle = await showSaveFilePicker();
const writable = await fileHandle.createWritable();
await writable.write(content);
await writable.close();
window.close();
}
async function restore(event) {
event.preventDefault();
event.stopImmediatePropagation();
let tabs = [];
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
// get tabs from text file (each line is a tab, an empty line indicates we can open a window with previous tabs)
contents.split("\n").forEach(async (line) => {
if (line == "" && tabs.length) {
// create new window with tabs in array
chrome.windows.create({
state: "maximized",
url: tabs,
});
tabs = []; // reset tabs array
} else {
// add tab to array
tabs.push(line);
}
});
window.close();
}
saveButton.addEventListener("click", save);
restoreButton.addEventListener("click", restore);