From 9ec4a86611fb924e014957597989fff1e6c9a455 Mon Sep 17 00:00:00 2001 From: eson Date: Tue, 17 Nov 2020 19:42:36 +0800 Subject: [PATCH] =?UTF-8?q?TODO:=20=E4=BF=AE=E6=AD=A3inject=20background?= =?UTF-8?q?=E7=9A=84=E6=A1=86=E6=9E=B6=E8=AE=BE=E8=AE=A1.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + example/.vscode/launch.json | 15 +++++ example/background.js | 27 ++++++++ example/inject.js | 7 ++ example/manifest.json | 22 ++++++ example/task.js | 1 + myblock/background/task.js | 5 ++ myblock/background/worker.js | 55 ++++++++++++--- myblock/base.js | 15 +++-- myblock/content/inject.js | 127 ++++++++++++++++++++++------------- myblock/manifest.json | 2 +- proxyserver/go.mod | 2 +- proxyserver/main.go | 6 +- 13 files changed, 221 insertions(+), 64 deletions(-) create mode 100644 example/.vscode/launch.json create mode 100644 example/background.js create mode 100644 example/inject.js create mode 100644 example/manifest.json create mode 100644 example/task.js create mode 100644 myblock/background/task.js diff --git a/.gitignore b/.gitignore index 19f3cf0..5540266 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.crx +proxyserver diff --git a/example/.vscode/launch.json b/example/.vscode/launch.json new file mode 100644 index 0000000..7978769 --- /dev/null +++ b/example/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "chrome", + "request": "launch", + "name": "Launch Chrome against localhost", + "url": "http://www.baidu.com", + "webRoot": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/example/background.js b/example/background.js new file mode 100644 index 0000000..a6049bd --- /dev/null +++ b/example/background.js @@ -0,0 +1,27 @@ + + +chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { + console.log(sender); + chrome.tabs.executeScript(sender.tab.id, { runAt: "document_end", file: "task.js"}, function (results) { + console.log(results); + }) + sendResponse({}); +}) + + + + +// chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { +// console.log(request, sender); +// }); + +chrome.webRequest.onBeforeRequest.addListener(function(details){ + if( details.url.startsWith("http://eson.config") ) { + // console.log(details); + var params = new URLSearchParams(details.url) + TaskUrl = params.get("taskurl"); + chrome.tabs.remove(details.tabId, function() { }); + return {cancel: true}; + } + },{'urls':[""]},['blocking']); + \ No newline at end of file diff --git a/example/inject.js b/example/inject.js new file mode 100644 index 0000000..435369f --- /dev/null +++ b/example/inject.js @@ -0,0 +1,7 @@ + + +setTimeout(function () { + chrome.runtime.sendMessage({}, function(resposne){ + console.log(resposne); + }) +}, 3000); \ No newline at end of file diff --git a/example/manifest.json b/example/manifest.json new file mode 100644 index 0000000..1618452 --- /dev/null +++ b/example/manifest.json @@ -0,0 +1,22 @@ +{ + "background": { + "scripts": [ + "background.js" + ] + }, + "content_scripts": [ { + "all_frames": true, + "js": [ + "inject.js" + ], + "matches": [ "" ], + "run_at": "document_end" + } ], + "description": "block all", + "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlurgt0Ykv740tjk1ebeiSX6UVVRRhxVvh+FvRMTe9PKzkAKUDEW2IjNUz1swxZA8ILnMvtyamAfiErTOxUFB8+zCADU/CK2YEhqUJo3tmHCg6EP2XJL220ZXjmIeft1AqJV1BmGRLhm8VnH8dJ2EThfcflx4JEdlh0/aLJr6UVjF2hPVX8JLAMTVjEfiC82KDNGgXDADqBm3E/6n+Dx+3KhgIYTXKIMk+qRVaOhjAJLh8a9OrDBwpylP5RDifTAyVVa9UOyoLNqynzC9oLabWUr1ovWAOiivhYknFCXnl5q971iNSFpmjc+ZW+aK+TRjMnJF84IeA170corVG3KgnwIDAQAB", + "manifest_version": 2, + "name": "ChromeProxyTest", + "permissions": ["background", "storage","tabs" , "activeTab", "webRequest", "webRequestBlocking", "", "webNavigation"], + "short_name": "ChromeProxyTest", + "version": "0.1.0" +} diff --git a/example/task.js b/example/task.js new file mode 100644 index 0000000..c96da6d --- /dev/null +++ b/example/task.js @@ -0,0 +1 @@ +window.location.href = "http://www.baidu.com"; \ No newline at end of file diff --git a/myblock/background/task.js b/myblock/background/task.js new file mode 100644 index 0000000..b421e57 --- /dev/null +++ b/myblock/background/task.js @@ -0,0 +1,5 @@ + +function ExecuteTask(response) { + window.location.href = response.url; +} +ExecuteTask() diff --git a/myblock/background/worker.js b/myblock/background/worker.js index ed3033d..791dda7 100644 --- a/myblock/background/worker.js +++ b/myblock/background/worker.js @@ -1,17 +1,29 @@ - -function GetTask() { - fetch(TaskUrl) +var task_manager = { } -chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { +function GetTask(sender) { + fetch(TaskUrl).then(function (response) { + task_manager[sender.tab.id] = response; + chrome.tabs.executeScript(sender.tab.id, { "runAt": "document_end", file: "background/task.js" }, function (results) { + }) + }).catch(function (reason) { + console.log(reason); + }) +} + +chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { switch (request.type) { - case MsgType.CONTENT: - console.log(request); - case MsgType.TIMEOUT: - // sendResponse({type: "error"}) + case BackgroundMsgType.CONTENT: + console.log(request, task_manager, sender); // 利用sender tab id 返回正确的任务id + case BackgroundMsgType.ERROR: + console.log(request, task_manager, sender); // 利用sender tab id 返回正确的任务id + case BackgroundMsgType.GETTASK: + // sendResponse({type: "error"}) } - sendResponse({type: MsgType.NEWURL, url: "https://playerduo.com/api/playerDuo-service-v2/rip113?lang=en&deviceType=browser"}); + // sendResponse({type: MsgType.NEWURL, url: "https://playerduo.com/api/playerDuo-service-v2/rip113?lang=en&deviceType=browser"}); + GetTask(sender); + sendResponse(); }); @@ -26,6 +38,29 @@ chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { +// 配置使用的监听 +chrome.webRequest.onBeforeRequest.addListener(function (details) { + if (details.url.startsWith("http://eson.config")) { + var params = new URLSearchParams(details.url) + TaskUrl = params.get("taskurl"); + chrome.tabs.remove(details.tabId, function () { }); + return { cancel: true }; + } +}, { 'urls': [""] }, ['blocking']); + + + + + + + + + + + + + + @@ -58,7 +93,7 @@ chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { // ); - + // fetch('https://playerduo.com/api/playerDuo-service-v2/rip113?lang=en&deviceType=browser').then(r => r.text()).then(result => { // // Result now contains the response text, do what you want... // console.log(result); diff --git a/myblock/base.js b/myblock/base.js index 4330c83..d6a1ad6 100644 --- a/myblock/base.js +++ b/myblock/base.js @@ -1,10 +1,17 @@ -const TaskUrl = "http://localhost:8820"; +var TaskUrl = "http://localhost:7123/task/get"; +const TaskIDKey = "chrome_proxy_tid_key" -const MsgType = { +const BackgroundMsgType = { + CONTENT: 'content', - NEWURL: 'newurl', - WAIT: 'wait', + GETTASK: 'gettask', TIMEOUT: 'timeout', ERROR: 'error', } + +const InjectMsgType = { + FETCH: 'fetch', + WAIT: 'wait', + ERROR: 'error', +} diff --git a/myblock/content/inject.js b/myblock/content/inject.js index 6f47945..1725856 100644 --- a/myblock/content/inject.js +++ b/myblock/content/inject.js @@ -1,57 +1,92 @@ -function Execute(response) { - window.location.href = response.url; - window.location.hash = response.tid -} -function TimeoutClient(tm) { - setTimeout(function () { - chrome.runtime.sendMessage({ type: MsgType.TIMEOUT }, function (response) { - switch (response.type) { - case MsgType.NEWURL: - Execute(response) - case MsgType.WAIT: - TimeoutClient(1000); - } - }); - }, tm); -} +var href = window.location.href; +var content = document.documentElement.innerHTML; + +var interval = setInterval(function(){ + GetTask(); +}, 6000) -var tm = 6000; -try { - var href = window.location.href; - var tid = window.location.hash; if (href.startsWith("https://playerduo.com")) { - var content = document.documentElement.innerHTML; - if ( - content.startsWith('
')
-  ) {
-    chrome.runtime.sendMessage(
-      {
-        type: MsgType.CONTENT,
-        tid: tid,
-        content: content,
-      },
-      function (response) {
-        console.log(response.type, response);
-        switch (response.type) {
-          case MsgType.NEWURL:
-            Execute(response);
-          case MsgType.WAIT:
-            tm = 1000;
-          default:
-        }
-      }
-    );
+  if (content.startsWith('
')) {
+    SendContent();
+    clearInterval(interval);
+    GetTask();
   }
-}  
-} catch (error) {
-    chrome.runtime.sendMessage({type: MsgType.ERROR, msg: error}) 
-} finally {
-    TimeoutClient(tm);
+}
+
+function SendContent() {
+  chrome.runtime.sendMessage({ type: BackgroundMsgType.CONTENT, content: content },
+    function (response) {
+      console.log(response.type, response);
+    })
+}
+
+function GetTask() {
+  chrome.runtime.sendMessage({ type: BackgroundMsgType.GETTASK }, function (response) {
+    console.log(response);
+  })
 }
 
 
 
 
+// var reset = {
+//   timeout: setTimeout(function () {
+//     chrome.runtime.sendMessage({ type: BackgroundMsgType.TIMEOUT }, function (response) { 
+//       console.log(response);
+//     })
+//     GetTask(1000);
+//   }, 7000),
+//   isCancel: false,
+// }
+
+
+
+// function GetTask(timeout) {
+//   chrome.runtime.sendMessage({ type: BackgroundMsgType.GETTASK }, function (response) {
+//     console.log("GetTask:", response.type, response);
+//     switch (response.type) {
+//       case InjectMsgType.WAIT:
+//         if (!reset.isCancel) {
+//           clearTimeout(reset.timeout);
+//           reset.isCancel = true;
+//         }
+//         setTimeout(function () {
+//           GetTask()
+//         }, timeout) // 递归获取请求
+//       case InjectMsgType.FETCH:
+//     }
+//   })
+// }
+
+// var href = window.location.href;
+// if (href.startsWith("https://playerduo.com")) {
+//   var content = document.documentElement.innerHTML;
+//   if (content.startsWith('
')) {
+//     chrome.runtime.sendMessage({ type: BackgroundMsgType.CONTENT, content: content },
+//       function (response) {
+//         console.log(response.type, response);
+//         if (response.type === BackgroundMsgType.GETTASK) {
+//           GetTask(1000); // 立即获取任务. 如果没有就等待
+//         };
+//       })
+//   }
+// }
+
+
+
+
+
+
+
+// chrome.runtime.onMessage.addListener(function (request) {
+//   if (request.type === BackgroundMsgType.CONTENT) {
+
+//   }
+
+//   // chrome.runtime.onMessage.removeListener(assignTextToTextareas);  //optional
+// });
+
+
diff --git a/myblock/manifest.json b/myblock/manifest.json
index 1699b90..2504df8 100644
--- a/myblock/manifest.json
+++ b/myblock/manifest.json
@@ -36,7 +36,7 @@
    "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlurgt0Ykv740tjk1ebeiSX6UVVRRhxVvh+FvRMTe9PKzkAKUDEW2IjNUz1swxZA8ILnMvtyamAfiErTOxUFB8+zCADU/CK2YEhqUJo3tmHCg6EP2XJL220ZXjmIeft1AqJV1BmGRLhm8VnH8dJ2EThfcflx4JEdlh0/aLJr6UVjF2hPVX8JLAMTVjEfiC82KDNGgXDADqBm3E/6n+Dx+3KhgIYTXKIMk+qRVaOhjAJLh8a9OrDBwpylP5RDifTAyVVa9UOyoLNqynzC9oLabWUr1ovWAOiivhYknFCXnl5q971iNSFpmjc+ZW+aK+TRjMnJF84IeA170corVG3KgnwIDAQAB",
    "manifest_version": 2,
    "name": "ChromeProxy",
-   "permissions": [  "storage","tabs" , "activeTab", "webRequest", "webRequestBlocking", "", "webNavigation"],
+   "permissions": ["background", "http://*/*", "https://*/*",  "storage","tabs" , "activeTab", "webRequest", "webRequestBlocking", "", "webNavigation"],
    "short_name": "ChromeProxy",
    "version": "0.1.0"
 }
diff --git a/proxyserver/go.mod b/proxyserver/go.mod
index be3b908..5f260a6 100644
--- a/proxyserver/go.mod
+++ b/proxyserver/go.mod
@@ -3,7 +3,7 @@ module git.nonolive.co/eson.hsm/proxyserver
 go 1.15
 
 require (
-	github.com/gin-gonic/gin v1.6.3 // indirect
+	github.com/gin-gonic/gin v1.6.3
 	github.com/go-playground/validator/v10 v10.4.1 // indirect
 	github.com/golang/protobuf v1.4.3 // indirect
 	github.com/json-iterator/go v1.1.10 // indirect
diff --git a/proxyserver/main.go b/proxyserver/main.go
index 704de30..ab85e65 100644
--- a/proxyserver/main.go
+++ b/proxyserver/main.go
@@ -2,7 +2,9 @@ package main
 
 import "github.com/gin-gonic/gin"
 
+var engine = gin.New()
+
 func main() {
-	eg := gin.New()
-	eg.GET("/task/get")
+
+	engine.Run(":7123")
 }