chromeworker/chromeproxy/background/worker.js

124 lines
2.9 KiB
JavaScript

console.log("background");
var task_manager = {
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
sendResponse({});
switch (request.type) {
case BackgroundMsgType.CONTENT:
FinishTask(sender, request.content);
break;
case BackgroundMsgType.ERROR:
ErrorTask(sender, request.error)
break;
case BackgroundMsgType.GETTASK:
GetTask(sender);
break;
case BackgroundMsgType.NOTWANT:
task = task_manager[sender.tab.id];
task.data.retry --;
if(task.data.retry >= 0) {
CaptureContent(task);
} else {
ErrorTask(sender, request.content);
}
break;
default:
break;
}
});
function GetTask(sender) {
fetch(GetTaskUrl).then(function (response) {
if (response.ok) {
response.json().then(function (task) {
CaptureContent(task);
})
} else {
console.log("error response:", response.text())
ErrorTask(sender, response.text());
}
}).catch(function (reason) {
console.log(reason);
ErrorTask(sender, reason);
})
}
function CaptureContent(task) {
if (task.code == 200) {
if(task.data.retry == undefined) {
task.data.retry = 1;
}
chrome.tabs.create({ url: task.data.url }, function (tab) {
task_manager[tab.id] = task;
if (task.data.content_condition) {
condition = `${task.data.content_condition}`
}
if (condition) {
chrome.tabs.executeScript(tab.id, { runAt: "document_end", code: condition }, function () {
chrome.tabs.executeScript(tab.id, { runAt: "document_end", file: "background/capture.js" });
});
} else {
chrome.tabs.executeScript(tab.id, { runAt: "document_end", file: "background/capture.js" });
}
});
}
}
function FinishTask(sender, content) {
var task = task_manager[sender.tab.id];
var formdata = new FormData();
formdata.append("taskid", task.data.taskid);
formdata.append("content", content);
delete task_manager[sender.tab.id];
chrome.tabs.remove(sender.tab.id);
fetch(FinishTaskUrl, { method: "POST", body: formdata }).then(function (response) {
if (response.ok) {
response.json().then(function (value) {
if (value.code == 200) {
GetTask(sender);
return
}
});
}
}).catch(function (error) {
ErrorTask(sender, error);
console.log(error)
return;
});
}
function ErrorTask(sender, error) {
var task = task_manager[sender.tab.id];
var formdata = new FormData();
formdata.append("taskid", task.data.taskid);
formdata.append("error", error);
fetch(ErrorTaskUrl, { method: "POST", body: formdata }, function (response) {
if (response.ok) {
response.json().then(function (value) {
if (value.code == 200) {
GetTask(sender);
return
}
});
}
}).then().catch(function (error) {
console.log(error)
return;
});
}