NovelBin/FirefoxExtension/background.js

87 lines
3.1 KiB
JavaScript

if (typeof browser === "undefined") {
var browser = chrome;
}
let autoRecordInterval = null;
let autoRecordAllowedPrefixes = []; // Global storage for allowed URL prefixes
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "login") {
fetch("http://192.168.0.226:25570/api/login", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: message.username, password: message.password })
})
.then(response => response.json())
.then(data => {
console.log("Login response:", data);
sendResponse(data);
})
.catch(err => sendResponse({ error: err.toString() }));
return true;
} else if (message.action === "register") {
fetch("http://192.168.0.226:25570/api/register", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: message.username, password: message.password })
})
.then(response => response.json())
.then(data => {
console.log("Registration response:", data);
sendResponse(data);
})
.catch(err => sendResponse({ error: err.toString() }));
return true;
} else if (message.action === "startAutoRecord") {
if (message.allowedPrefixes) {
autoRecordAllowedPrefixes = message.allowedPrefixes
.split(",")
.map(s => s.trim())
.filter(s => s.length > 0);
} else {
autoRecordAllowedPrefixes = [];
}
if (autoRecordInterval) {
clearInterval(autoRecordInterval);
}
autoRecordInterval = setInterval(() => {
browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs && tabs.length > 0) {
const currentUrl = tabs[0].url;
let recordUrl = false;
for (let prefix of autoRecordAllowedPrefixes) {
if (currentUrl.startsWith(prefix)) {
recordUrl = true;
break;
}
}
if (recordUrl) {
fetch("http://192.168.0.226:25570/record", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: currentUrl })
})
.then(response => response.json())
.then(data => console.log("Recorded URL:", data))
.catch(err => console.error("Recording error:", err));
} else {
console.log("URL does not match allowed prefixes, skipping: " + currentUrl);
}
}
});
}, message.interval || 10000);
sendResponse({ success: true, message: "Auto recording started" });
return true;
} else if (message.action === "stopAutoRecord") {
if (autoRecordInterval) {
clearInterval(autoRecordInterval);
autoRecordInterval = null;
}
sendResponse({ success: true, message: "Auto recording stopped" });
return true;
}
});