Refactored project

This commit is contained in:
Maxim Stewart 2020-01-31 20:43:21 -06:00
parent 42269c22b4
commit ed12f312bb
12 changed files with 435 additions and 402 deletions

View File

@ -4,8 +4,8 @@ Easy Session Manager allows you to manage your Firefox session by backing up or
# Download # Download
https://addons.mozilla.org/en-US/firefox/addon/easy-session-manager/ https://addons.mozilla.org/en-US/firefox/addon/easy-session-manager/
# Version: 0.2.1.3 # Version: 0.2.1.0
Improved width of SweetAlert windows. Refactored code and added tab count per session.
# Images # Images
![1 Default interface with no sessions. ](images/pic1.png) ![1 Default interface with no sessions. ](images/pic1.png)

View File

@ -1,8 +1,8 @@
{ {
"manifest_version": 2, "manifest_version": 2,
"name": " Easy Session Manager", "name": " Easy Session Manager",
"version": "0.2.1.3", "version": "0.2.1.0",
"description": " Easy Session Manager allows you to manage your Firefox session by backing up or loading your saved sessions.", "description": "Easy Session Manager allows you to manage your Firefox session by backing up or loading your saved sessions.",
"applications": { "applications": {
"gecko": { "gecko": {
@ -27,7 +27,7 @@
"browser_action": { "browser_action": {
"default_icon": "images/icons/sessionManager.png", "default_icon": "images/icons/sessionManager.png",
"default_title": " Easy Session Manager", "default_title": "Easy Session Manager",
"default_popup": "pages/sessionManager.html" "default_popup": "pages/sessionManager.html"
} }

View File

@ -29,7 +29,7 @@ body, html {
</span> </span>
<script src="../scripts/sweetalert.js"></script> <script src="../scripts/libs/sweetalert.js"></script>
<script src="../scripts/background.js"></script> <script src="../scripts/background.js"></script>
</body> </body>
</html> </html>

View File

@ -42,9 +42,10 @@
<a id="downloadAnchorElem" href="#"></a> <a id="downloadAnchorElem" href="#"></a>
<script src="../scripts/libs/sweetalert.js"></script>
<script src="../scripts/utils.js"></script> <script src="../scripts/utils.js"></script>
<script src="../scripts/actions.js"></script>
<script src="../scripts/session-manager.js"></script>
<script src="../scripts/events.js"></script> <script src="../scripts/events.js"></script>
<script src="../scripts/sweetalert.js"></script>
<script src="../scripts/sessionManager.js"></script>
</body> </body>
</html> </html>

81
src/scripts/actions.js Normal file
View File

@ -0,0 +1,81 @@
const messageWindow = (type = "warning", message = "No message passed in...") => {
swal(message, { icon: type, });
}
const getSavedSessionIDs = () => {
storageApi.get(null).then((results) => {
let keys = Object.keys(results);
for (let key of keys) {
appendToSavedSessionsList(key);
}
});
}
const windowMaker = (i, keysLength, keys, json) => {
for (; i < keysLength; i++) {
let store = json[keys[i]];
let urls = [];
for (let j = 0; j < store.length; j++) {
urls.push(store[j].link);
}
windowApi.create({ url: urls });
}
}
const saveToStorage = (name, data, action = "undefined", willReplace = false) => {
storageApi.get(name).then((results) => {
try {
// If save finds a session successfully then check if replacing
const json = JSON.parse(results[name]);
if (!willReplace) {
swal({
title: "Replace?",
text: "Found a session with that name! Do you want to replace it?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willReplace) => {
if (willReplace) {
storageApi.set({[name]: data});
messageWindow("warning", "Overwrote session...");
} else {
messageWindow("warning", "Canceled " + action + "...");
}
});
} else {
storageApi.set({[name]: data});
messageWindow("warning", "Overwrote session...");
}
} catch (e) {
if (action !== "edit") {
appendToSavedSessionsList(name);
messageWindow("success", "Saved session...");
storageApi.set({[name]: data});
} else {
messageWindow("warning", "Overwrote session...");
storageApi.set({[name]: data});
}
}
});
}
const deleteFromStorage = (elm = null) => {
swal({
title: "Are you sure?",
text: "Do you wish to delete session:\n" + elm.innerText + "?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
storageApi.remove(elm.innerText).then(() => {
elm.parentElement.removeChild(elm);
});
selectedItem = null; // reset selectedItem
messageWindow("success", "Deleted session successfully...");
} else {
messageWindow("warning", "Canceled deletion...");
}
});
}

View File

@ -1,7 +1,7 @@
const regexp = /^[a-zA-Z0-9-_]+$/; // Alphanumeric, dash, underscore const message1 = "What is this session's name? Allowed: a-z, A-Z, -, _";
const regexp = /^[a-zA-Z0-9-_]+$/; // Alphanumeric, dash, underscore
const processor = (obj, enteryName = '', const processor = (obj, enteryName = '', message = message1) => {
message = "What is this session's name? Allowed: a-z, A-Z, -, _") => {
let data = obj.target.result; let data = obj.target.result;
let inputTag = document.createElement("INPUT"); let inputTag = document.createElement("INPUT");
inputTag.value = enteryName; inputTag.value = enteryName;
@ -13,29 +13,24 @@ const processor = (obj, enteryName = '',
}).then((value) => { }).then((value) => {
if (value) { if (value) {
enteryName = inputTag.value.replace(/ /g, "_"); enteryName = inputTag.value.replace(/ /g, "_");
if (enteryName) {
if (enteryName.search(regexp) == -1) {
processor(obj, enteryName, "Please try again...\nAllowed: a-z, A-Z, -, _")
return ;
}
try { if (enteryName.length < 0 || enteryName.length > 54 || enteryName.search(regexp) == -1) {
console.log("Importing session..."); processor(obj, "", "Allowed: a-z, A-Z, 0-9, -, _ Please try again...\nName too long or none provided; or, unacceptable character used.");
JSON.parse(data); return ;
browser.storage.local.set({[enteryName]: data}); }
swal("Imported file successfully.", {
icon: "success", try {
}); console.log("Importing session...");
} catch (e) { JSON.parse(data);
swal("Failed to import data. Not a JSON parsable file.", { browser.storage.local.set({[enteryName]: data});
icon: "error", swal("Imported file successfully.", {
}); icon: "success",
return ;
}
} else {
swal("Canceled import.", {
icon: "warning",
}); });
} catch (e) {
swal("Failed to import data. Not a JSON parsable file.", {
icon: "error",
});
return ;
} }
} else { } else {
swal("Canceled import.", { swal("Canceled import.", {

View File

@ -1,11 +1,4 @@
let selectedItem = null; getSavedSessionIDs();
const toggleSelect = (source, name) => {
let checkboxes = document.getElementsByName(name);
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
document.addEventListener("click", (e) => { document.addEventListener("click", (e) => {
if (e.button == 0) { // Left click if (e.button == 0) { // Left click
@ -27,10 +20,7 @@ document.addEventListener("click", (e) => {
} else if (name == "import") { } else if (name == "import") {
importSession(); importSession();
} else if (name == "donate") { } else if (name == "donate") {
var dlAnchorElem = document.getElementById('downloadAnchorElem'); doUrlAction("https://www.paypal.me/ITDominator",);
dlAnchorElem.setAttribute("href", "https://www.paypal.me/ITDominator");
dlAnchorElem.setAttribute("_blank", "");
dlAnchorElem.click();
} }
if (e.target.tagName == "LI" && e.target.className.includes("sessionLI")) { if (e.target.tagName == "LI" && e.target.className.includes("sessionLI")) {
@ -55,39 +45,9 @@ document.addEventListener("dblclick", (e) => {
if (e.button == 0) { // Left click if (e.button == 0) { // Left click
if (e.target.tagName == "LI" && e.target.className.includes("sessionLI")) { if (e.target.tagName == "LI" && e.target.className.includes("sessionLI")) {
selectedItem = e.target; selectedItem = e.target;
let id = selectedItem.innerText.trim();
selectedItem.setAttribute("class", "sessionLI selected"); selectedItem.setAttribute("class", "sessionLI selected");
try { preLoadSession(id);
let id = e.target.innerText.trim();
storage.get(id).then(storageResults => {
let json = JSON.parse(storageResults[id]);
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
let replaceTabs = document.getElementsByName("replaceTabs")[0];
let selectiveOpen = document.getElementsByName("selectiveOpen")[0];
if (!selectiveOpen.checked) {
loadSession(json, replaceTabs.checked);
} else {
let container = selectionWindow(json, keys, keysLength);
swal("Selective Open", {
content: container,
buttons: true,
}).then((willOpen) => {
if (willOpen) {
json = selectionData(container, keys, keysLength);
keysLength = Object.keys(json).length;
if (keysLength > 0) {
loadSession(json, replaceTabs.checked);
} else {
messageWindow("warning", "Canceled operation; no tabs were selected...");
}
}
});
}
});
} catch (e) {
console.log(e);
}
} }
} }
}); });

View File

@ -0,0 +1,250 @@
const message1 = "[ Session Name ] Allowed: a-z, A-Z, 0-9, -, _";
const message2 = "Allowed: a-z, A-Z, 0-9, -, _ Please try again...\nName too long or none provided; or, unacceptable character used.";
const storageApi = browser.storage.local;
const tabsApi = browser.tabs;
const windowApi = browser.windows;
const regexp = /^[a-zA-Z0-9-_]+$/; // Alphanumeric, dash, underscore
const saveSession = (elm = null, message = message1) => {
let inputTag = document.createElement("INPUT");
let willReplace = false;
inputTag.value = new Date().toLocaleString().split(',')[0].replace(/\//g, '-');
if (elm !== null) {
inputTag.value = elm.innerText;
willReplace = true;
}
windowApi.getAll({ populate: true, windowTypes: ["normal"] }).then((windows) => {
let sessionData = getSessionData(windows);
let keys = Object.keys(sessionData);
let keysLength = Object.keys(sessionData).length;
let container = generateSelectionWindow(sessionData, keys, keysLength);
container.prepend(inputTag);
swal(message, {
content: container,
buttons: true,
customClass: 'swal-modal',
}).then((value) => {
if (value) {
let enteryName = inputTag.value.replace(/ /g, "_");
if (enteryName.length < 0 || enteryName.length > 54 || enteryName.search(regexp) == -1) {
saveSession(elm, message2);
return ;
}
console.log("Saving session...");
sessionData = getSelectionData(container, keys, keysLength);
saveToStorage(enteryName, JSON.stringify(sessionData), "save", willReplace);
} else {
messageWindow("warning", "Canceled save...");
}
});
});
}
const editSession = (elm = null, message = message1) => {
let id = elm.innerText;
let inputTag = document.createElement("INPUT");
let newSessionCheckTag = document.createElement("INPUT");
let labelTag = document.createElement("LABEL");
let brTag = document.createElement("BR");
inputTag.value = id;
newSessionCheckTag.type = "checkbox";
newSessionCheckTag.id = "newSession";
newSessionCheckTag.checked = false;
labelTag.innerText = "Create New Session";
labelTag.htmlFor = "newSession";
storageApi.get(id).then((results) => {
let json = JSON.parse(results[id]);
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
let container = generateSelectionWindow(json, keys, keysLength);
container.prepend(labelTag);
container.prepend(newSessionCheckTag);
container.prepend(brTag);
container.prepend(inputTag);
console.log("Editing session...");
swal(message, {
content: container,
buttons: true,
customClass: 'swal-modal',
}).then((value) => {
if (value) {
let newName = inputTag.value.replace(/ /g, "_");
if (newName.length < 0 || newName.length > 54 || newName.search(regexp) == -1) {
editSession(elm, message2);
return ;
}
json = getSelectionData(container, keys, keysLength);
// If creating from collection new session
if (newSessionCheckTag.checked) {
if (newName !== elm.innerText) {
newName = checkSessionListForDuplicate(newName);
saveToStorage(newName, JSON.stringify(json), "save");
} else { // Enforce unique name
let min = 1;
let max = 200000;
var random = Math.floor(Math.random() * (+max - +min)) + +min;
newName += "-" + random + "-" + Math.floor(Math.random() * (+10 - +1)) + +1;
saveToStorage(newName, JSON.stringify(json), "edit");
}
} else {
// If not creating new session and diff name enforced; generate new name
if (newName !== elm.innerText) {
newName = checkSessionListForDuplicate(newName);
storageApi.get(id).then((results) => {
storageApi.remove(id);
saveToStorage(newName, JSON.stringify(json), "edit");
}).then(() => {
elm.textContent = newName;
});
} else { // Replace found session
saveToStorage(newName, JSON.stringify(json), "edit", true);
}
}
} else {
messageWindow("warning", "Canceled edit...");
}
});
});
}
const downloadSession = (elm = null) => {
let pTag = document.createElement("P");
let inputTag = document.createElement("INPUT");
let chkBoxTag = document.createElement("INPUT");
let lblTag = document.createElement("LABEL");
let brTag = document.createElement("BR");
let aTagElm = document.getElementById('downloadAnchorElem');
let text = document.createTextNode("Append Date?");
let id = elm.innerText;
let fileName = "session:" + id + ".json";
chkBoxTag.type = "checkbox";
inputTag.value = fileName;
chkBoxTag.id = "chkbx";
lblTag.htmlFor = "chkbx";
lblTag.append(text);
pTag.append(lblTag);
pTag.append(chkBoxTag);
pTag.append(brTag);
pTag.append(inputTag);
swal("Download Session?", {
content: pTag,
buttons: true,
customClass: 'swal-modal',
}).then((willDl) => {
if (willDl) {
if (chkBoxTag.checked) {
fileName = "session:" + id + ":" +
new Date().toLocaleString().split(',')[0].replace(/\//g, "-") + ".json";
}
storageApi.get(id).then((results) => {
let json = JSON.parse(results[id]);
console.log("Downloading: " + id);
let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json));
doUrlAction(dataStr, fileName, true);
});
}
});
}
const preLoadSession = (id) => {
storageApi.get(id).then(results => {
try {
let json = JSON.parse(results[id]);
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
let replaceTabs = document.getElementsByName("replaceTabs")[0];
let selectiveOpen = document.getElementsByName("selectiveOpen")[0];
if (!selectiveOpen.checked) {
loadSession(json, replaceTabs.checked);
} else {
let container = generateSelectionWindow(json, keys, keysLength);
swal("Selective Open", {
content: container,
buttons: true,
}).then((willOpen) => {
if (willOpen) {
json = getSelectionData(container, keys, keysLength);
keysLength = Object.keys(json).length;
if (keysLength > 0) {
loadSession(json, replaceTabs.checked);
} else {
messageWindow("warning", "Canceled Operation: No tabs were selected...");
}
}
});
}
} catch (e) {
messageWindow("error", "Couldn't load session:\n" + e);
}
});
}
const loadSession = (json = null, replaceTabs = false) => {
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
try {
browser.windows.getAll().then(windows => {
windowApi.getCurrent({populate: true}).then(currentWindow => {
let wasCurrentTabId = null;
if (replaceTabs) { // Clear all windows but main then load...
if (keysLength == 0) {
messageWindow("error", "Canceled operation; no tabs in session...");
return ;
}
for (let i = 0; i < windows.length; i++) {
if (currentWindow.id != windows[i].id) {
windowApi.remove(windows[i].id);
} else {
let ids = [];
currentWindow.tabs.forEach(tab => {
if (!tab.active) {
ids.push(tab.id);
} else {
wasCurrentTabId = tab.id;
}
});
tabsApi.remove(ids);
}
}
// First load tabs to current window.
let store = json[keys[0]];
store.forEach(tab => {
tabsApi.create({ url: tab.link });
});
tabsApi.remove(wasCurrentTabId);
// If more than one window, load tabs to new windows.
if (keysLength > 1) {
windowMaker(1, keysLength, keys, json)
}
} else { // Load into new windows...
if (keysLength == 1) {
windowMaker(0, keysLength, keys, json)
} else if (keysLength == 0) {
messageWindow("error", "Canceled operation; no tabs in session...");
}
}
});
});
} catch (e) {
messageWindow("error", "Couldn't load session:\n" + e);
}
}

View File

@ -1,236 +0,0 @@
const storage = browser.storage.local;
const windowSys = browser.windows;
const regexp = /^[a-zA-Z0-9-_]+$/; // Alphanumeric, dash, underscore
const saveSession = (elm = null, message = "[ Session Name ] Allowed: a-z, A-Z, 0-9, -, _") => {
let inputTag = document.createElement("INPUT");
inputTag.value = new Date().toLocaleString().split(',')[0].replace(/\//g, '-');
if (elm !== null)
inputTag.value = elm.innerText;
windowSys.getAll({ populate: true, windowTypes: ["normal"] }).then((windows) => {
let sessionData = {};
for (let i = 0; i < windows.length; i++) {
let links = [];
for (var ii = 0; ii < windows[i].tabs.length; ii++) {
if (!windows[i].tabs[ii].url.includes("about:")) {
links.push(
{"link" : windows[i].tabs[ii].url.trim()}
);
}
}
sessionData["WindowID:" + windows[i].id] = links;
}
let keys = Object.keys(sessionData);
let keysLength = Object.keys(sessionData).length;
let container = selectionWindow(sessionData, keys, keysLength);
container.prepend(inputTag);
swal(message, {
content: container,
buttons: true,
customClass: 'swal-modal',
}).then((value) => {
if (value) {
let enteryName = inputTag.value.replace(/ /g, "_");
if (enteryName) {
if (enteryName.search(regexp) == -1) {
saveSession("Please try again...\nAllowed: a-z, A-Z, 0-9, -, _")
return ;
}
console.log("Saving session...");
sessionData = selectionData(container, keys, keysLength);
saveToStorage(enteryName, JSON.stringify(sessionData));
} else {
messageWindow("warning", "Canceled save...");
}
} else {
messageWindow("warning", "Canceled save...");
}
});
});
}
const editSession = (elm = null, message = "Editing selected session...\nAllowed: a-z, A-Z, 0-9, -, _") => {
let id = elm.innerText;
let inputTag = document.createElement("INPUT");
let checkedTag = document.createElement("INPUT");
let labelTag = document.createElement("LABEL");
let brTag = document.createElement("BR");
inputTag.value = id;
checkedTag.type = "checkbox";
checkedTag.id = "newSession";
checkedTag.checked = false;
labelTag.innerText = "Create New Session";
labelTag.htmlFor = "newSession";
storage.get(id).then((storageResults) => {
let json = JSON.parse(storageResults[id]);
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
let container = selectionWindow(json, keys, keysLength);
container.prepend(labelTag);
container.prepend(checkedTag);
container.prepend(brTag);
container.prepend(inputTag);
swal(message, {
content: container,
buttons: true,
customClass: 'swal-modal',
}).then((value) => {
if (value) {
let newName = inputTag.value.replace(/ /g, "_");
if (newName) {
if (newName.search(regexp) == -1) {
editSession("Please try again...\nAllowed: a-z, A-Z, 0-9, -, _")
return ;
}
json = selectionData(container, keys, keysLength);
if (checkedTag.checked) { // if creating from collection new session
if (newName !== elm.innerText) {
newName = checkSessionListForDuplicate(newName);
saveToStorage(newName, JSON.stringify(json), false);
} else { // enforce unique name
let min = 1;
let max = 200000;
var random = Math.floor(Math.random() * (+max - +min)) + +min;
newName += "-" + random + "-" + Math.floor(Math.random() * (+10 - +1)) + +1;
saveToStorage(newName, JSON.stringify(json), false);
}
} else {
if (newName !== elm.innerText) { // if not creating new session and diff name rename
newName = checkSessionListForDuplicate(newName);
storage.get(id).then((storageResults) => {
storage.remove(id);
saveToStorage(newName, JSON.stringify(json), true);
}).then(() => {
elm.textContent = newName;
});
} else { // just replace
saveToStorage(newName, JSON.stringify(json), true);
}
}
} else {
messageWindow("warning", "Canceled edit...");
}
} else {
messageWindow("warning", "Canceled edit...");
}
});
});
}
const importSession = () => {
browser.tabs.create({
url: browser.extension.getURL("../pages/import.html"),
active: true
});
}
const downloadSession = (elm = null) => {
let pTag = document.createElement("P");
let inputTag = document.createElement("INPUT");
let chkBoxTag = document.createElement("INPUT");
let lblTag = document.createElement("LABEL");
let brTag = document.createElement("BR");
var dlAnchorElem = document.getElementById('downloadAnchorElem');
let text = document.createTextNode("Append Date?");
let id = elm.innerText;
let fileName = "session:" + id + ".json";
chkBoxTag.type = "checkbox";
inputTag.value = fileName;
chkBoxTag.id = "chkbx";
lblTag.htmlFor = "chkbx";
lblTag.append(text);
pTag.append(lblTag);
pTag.append(chkBoxTag);
pTag.append(brTag);
pTag.append(inputTag);
swal("Download Session?", {
content: pTag,
buttons: true,
customClass: 'swal-modal',
}).then((willDl) => {
if (willDl) {
if (chkBoxTag.checked) {
fileName = "session:" + id + ":" +
new Date().toLocaleString().split(',')[0].replace(/\//g, "-") + ".json";
}
storage.get(id).then((storageResults) => {
let json = JSON.parse(storageResults[id]);
let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json));
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", fileName);
dlAnchorElem.setAttribute("target", "");
dlAnchorElem.click();
});
}
});
}
const loadSession = (json = null, replaceTabs = false) => {
console.log("Loading session...");
let keys = Object.keys(json);
let keysLength = Object.keys(json).length;
try {
browser.windows.getAll().then(windows => {
windowSys.getCurrent({populate: true}).then(currentWindow => {
let wasCurrentTabId = null;
if (replaceTabs) { // Clear all windows but main then load...
if (keysLength == 0) {
messageWindow("error", "Canceled operation; no tabs in session...");
return ;
}
for (let i = 0; i < windows.length; i++) {
if (currentWindow.id != windows[i].id) {
windowSys.remove(windows[i].id);
} else {
let ids = [];
currentWindow.tabs.forEach(tab => {
if (!tab.active) {
ids.push(tab.id);
} else {
wasCurrentTabId = tab.id;
}
});
browser.tabs.remove(ids);
}
}
// First load tabs to current window.
let store = json[keys[0]];
store.forEach(tab => {
browser.tabs.create({ url: tab.link });
});
browser.tabs.remove(wasCurrentTabId);
// If more than one window, load tabs to new windows.
if (keysLength > 1) {
windowMaker(1, keysLength, keys, json)
}
} else { // Load into new windows...
if (keysLength == 1) {
windowMaker(0, keysLength, keys, json)
} else if (keysLength == 0) {
messageWindow("error", "Canceled operation; no tabs in session...");
}
}
});
});
} catch (e) { console.log(e); }
}
getSavedSessionIDs();

View File

@ -1,95 +1,9 @@
const messageWindow = (type = "warning", message = "No message passed in...") => { let selectedItem = null;
swal(message, { icon: type, });
}
const getSavedSessionIDs = () => {
console.log("Getting saved sessions...");
storage.get(null).then((storageResults) => {
let keys = Object.keys(storageResults);
for (let key of keys) {
appendToSavedSessionsList(key);
}
});
}
const appendToSavedSessionsList = (enteryName) => {
let liTag = document.createElement("LI");
let text = document.createTextNode(enteryName.trim());
liTag.setAttribute("name", enteryName.trim());
liTag.className = "sessionLI";
liTag.append(text);
document.getElementById("savedSessions").append(liTag);
}
const checkSessionListForDuplicate = (newName) => {
let sessions = document.getElementById("savedSessions").querySelectorAll("li");
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].innerText === newName) {
let min = 1;
let max = 200000;
var random = Math.floor(Math.random() * (+max - +min)) + +min;
newName += "-" + random + "-" + Math.floor(Math.random() * (+10 - +1)) + +1;
}
}
return newName;
}
const windowMaker = (i, keysLength, keys, json) => {
for (; i < keysLength; i++) {
let store = json[keys[i]];
let urls = [];
for (let j = 0; j < store.length; j++) {
urls.push(store[j].link);
}
windowSys.create({ url: urls });
}
}
const saveToStorage = (name, data, fromEdit = false) => {
storage.get(name).then((storageResults) => {
let json = null;
try {
json = JSON.parse(storageResults[name]);
messageWindow("warning", "Overwrote session...");
} catch (e) {
if (fromEdit) { // minor logic fix
messageWindow("warning", "Overwrote session...");
} else {
appendToSavedSessionsList(name);
messageWindow("success", "Saved session...");
}
} finally {
storage.set({[name]: data});
}
});
}
const deleteFromStorage = (elm = null) => {
swal({
title: "Are you sure?",
text: "Do you wish to delete session:\n" + elm.innerText + "?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
storage.remove(elm.innerText).then(() => {
elm.parentElement.removeChild(elm);
});
selectedItem = null; // reset selectedItem
messageWindow("success", "Deleted session successfully...");
} else {
messageWindow("warning", "Canceled deletion...");
}
});
}
// UI supporters
/* Selection Process */ /* Selection Process */
const generateSelectionWindow = (json = "", keys = null, keysLength = 0) => {
const selectionWindow = (json = "", keys = null, keysLength = 0) => {
let container = document.createElement("DIV"); let container = document.createElement("DIV");
let ulTemplate = document.querySelector('#ulTemplate'); let ulTemplate = document.querySelector('#ulTemplate');
let liTemplate = document.querySelector('#liTemplate'); let liTemplate = document.querySelector('#liTemplate');
@ -132,7 +46,50 @@ const selectionWindow = (json = "", keys = null, keysLength = 0) => {
return container; return container;
} }
const selectionData = (container = null, keys = null, keysLength = 0) => { const checkSessionListForDuplicate = (newName) => {
let sessions = document.getElementById("savedSessions").querySelectorAll("li");
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].innerText === newName) {
let min = 1;
let max = 200000;
let random = Math.floor(Math.random() * (+max - +min)) + +min;
newName += "-" + random + "-" + Math.floor(Math.random() * (+10 - +1)) + +1;
}
}
return newName;
}
const appendToSavedSessionsList = (enteryName) => {
let liTag = document.createElement("LI");
let text = document.createTextNode(enteryName.trim());
liTag.className = "sessionLI";
liTag.setAttribute("name", enteryName.trim());
liTag.append(text);
document.getElementById("savedSessions").append(liTag);
}
// Generics
const getSessionData = (windows) => {
let sessionData = {};
for (let i = 0; i < windows.length; i++) {
let links = [];
for (var ii = 0; ii < windows[i].tabs.length; ii++) {
if (!windows[i].tabs[ii].url.includes("about:")) {
links.push(
{"link" : windows[i].tabs[ii].url.trim()}
);
}
}
sessionData["WindowID:" + windows[i].id] = links;
}
return sessionData;
}
const getSelectionData = (container = null, keys = null, keysLength = 0) => {
let sessionData = {}; let sessionData = {};
let ulTags = container.querySelectorAll("ul"); let ulTags = container.querySelectorAll("ul");
@ -155,3 +112,28 @@ const selectionData = (container = null, keys = null, keysLength = 0) => {
return sessionData; return sessionData;
} }
const doUrlAction = (url = "https://www.paypal.me/ITDominator", fileName = "", isDownload = false) => {
let aTagElm = document.getElementById('downloadAnchorElem');
aTagElm.setAttribute("href", url);
if (isDownload)
aTagElm.setAttribute("download", fileName);
aTagElm.setAttribute("_blank", "");
aTagElm.click();
}
const importSession = () => {
browser.tabs.create({
url: browser.extension.getURL("../pages/import.html"),
active: true
});
}
const toggleSelect = (source, name) => {
let checkboxes = document.getElementsByName(name);
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}