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; var execCode = `window.location.href = "${task.data.url}";` if(task.data.content_condition) { execCode += `PassContentCondition = ${task.data.content_condition};` } chrome.tabs.executeScript(sender.tab.id, {runAt: "document_end", code: execCode}) 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 URL(details.url).searchParams; UpdateHost(params.get("taskurl")) chrome.tabs.remove(details.tabId); chrome.tabs.query({currentWindow: true}, function(tabs) { var count = 0 for(var tab of tabs) { if(!tab.url.startsWith("chrome://") ) { count++; chrome.tabs.executeScript(tab.id, {runAt: "document_end", code: `window.location.href = "${Host}"` }) } else { chrome.tabs.remove(tab.id); } } for(var i = count; i < WorkerNumber;i++) { chrome.tabs.create({url: `${Host}`}); } }) return { cancel: true }; } }, { 'urls': [""] }, ['blocking']);