101 lines
2.7 KiB
JavaScript
101 lines
2.7 KiB
JavaScript
|
|
var task_manager = {
|
|
}
|
|
|
|
|
|
function GetTask(sender) {
|
|
fetch(GetTaskUrl).then(function (response) {
|
|
if (response.ok) {
|
|
response.json().then(function (task) {
|
|
if(task.code == 200) {
|
|
task_manager[sender.tab.id] = task;
|
|
chrome.tabs.executeScript(sender.tab.id, {runAt: "document_end", code: `window.location.href = "${task.data.url}"` }, function (results) {
|
|
})
|
|
Tell(sender, InjectMsgType.FETCH);
|
|
} else {
|
|
Tell(sender, InjectMsgType.NOTASK);
|
|
}
|
|
})
|
|
} else {
|
|
// ErrorTask(sender, "error response:" + response.text())
|
|
console.log("error response:",response.text())
|
|
}
|
|
}).catch(function (reason) {
|
|
console.log(reason);
|
|
// GetTask();
|
|
})
|
|
}
|
|
|
|
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);
|
|
console.log(task.data.taskid);
|
|
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){
|
|
// TODO: 汇报错误
|
|
// ErrorTask(sender, error);
|
|
console.log(error)
|
|
GetTask(sender);
|
|
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});
|
|
}
|
|
|
|
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)
|
|
GetTask(sender);
|
|
break;
|
|
case BackgroundMsgType.GETTASK:
|
|
GetTask(sender);
|
|
break;
|
|
case BackgroundMsgType.NOTWANT:
|
|
Tell(sender,InjectMsgType.WAIT);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
});
|
|
|
|
function Tell(sender, jnjectType) {
|
|
try {
|
|
chrome.tabs.sendMessage(sender.tab.id , {type: jnjectType})
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
}
|
|
|
|
// 配置使用的监听
|
|
chrome.webRequest.onBeforeRequest.addListener(function (details) {
|
|
if (details.url.startsWith("http://eson.config")) {
|
|
var params = new URLSearchParams(details.url)
|
|
GetTaskUrl = params.get("taskurl");
|
|
chrome.tabs.remove(details.tabId, function () { });
|
|
return { cancel: true };
|
|
}
|
|
}, { 'urls': ["<all_urls>"] }, ['blocking']); |