main.js
var windowId;
var storage = browser.storage.local;
async function downloadStorage(){
// console.log('downloadStorage');
const req = await fetch('http://searchmark.localhost/load/');
const marks = await req.json();
// storage.set(marks);
console.log('downloaded');
// console.log(marks);
// const all = await storage.get(null);
}
async function setup(){
const isSetup = (await storage.get('isSetup')).isSetup;
if (isSetup!='true'){
await downloadStorage();
}
await storage.set({"isSetup":"true"});
const markButton = document.querySelector(".tlf-tagmark .mark");
markButton.addEventListener("click", save);
browser.tabs.onActivated.addListener(updateContent);
browser.tabs.onUpdated.addListener(updateContent);
window.addEventListener("unload", save);
document.addEventListener('keydown',
function(event){
if (event.keyCode == 27){
event.preventDefault();
event.stopPropagation();
save();
}
}
);
}
async function upload(){
// const curSecs = Date.now();
// const tenMins = 1000*60*10;
// const lastSave = (await storage.get('lastSave')).lastSave;
// if (forceUpload || (lastSave != null && lastSave > (curSecs - tenMins)))return;
console.log('saving to server');
// await storage.set({"lastSave":curSecs});
const allMarks = await storage.get(null);
const formData = new FormData();
formData.append("marks",JSON.stringify(allMarks));
// console.log('uploading');
// console.log(allMarks);
const postOptions = {
method: 'POST',
body: formData,
}
const request = await fetch('http://searchmark.localhost/save/', postOptions);
const response = await request.text();
// console.log('response from server');
// console.log(response);
}
async function save(shouldForceUpload){
const tabs = await browser.tabs.query({windowId: windowId, active: true});
const tab = tabs[0];
const url = tab.url;
let item = await storage.get(url);
if (item == null) item = {};
const tags = document.querySelector('.tlf-tagmark [name="tags"]').value;
const notes = document.querySelector('.tlf-tagmark [name="notes"]').value;
item[url] = {
url: url,
tags: tags,
notes: notes,
};
await storage.set(item);
await upload(shouldForceUpload);
}
async function updateContent(){
const tabs = await browser.tabs.query({windowId: windowId, active: true});
const url = tabs[0].url;
const pageMark = await storage.get(url);
// console.log('get from storage for "'+url+'"');
// console.log(pageMark);
const tags = document.querySelector('.tlf-tagmark [name="tags"]').value = pageMark[url]?.tags ?? '';
const notes = document.querySelector('.tlf-tagmark [name="notes"]').value = pageMark[url]?.notes ?? '';
}
browser.windows.getCurrent({populate: true}).then((windowInfo) => {
windowId = windowInfo.id;
updateContent();
});
setup();