Selaa lähdekoodia

修复子窗口脚本加载问题

PUGE 8 kuukautta sitten
vanhempi
sitoutus
e94b20a569
4 muutettua tiedostoa jossa 160 lisäystä ja 166 poistoa
  1. 4 2
      config.json
  2. 75 0
      index.html
  3. 58 33
      main.js
  4. 23 131
      preload.js

+ 4 - 2
config.json

@@ -1,12 +1,14 @@
 {
-    "enterURL": "https://demos.run/soundSynthesis/index1.html",
+    "enterURL": "./index.html",
     "width": 960,
     "height": 570,
     "webPreferences": {
         "webSecurity": false,
+        "contextIsolation": true,
         "nodeIntegration": false,
         "nativeWindowOpen": false,
-        "preload": "C:/Users/mail/Documents/GitHub/myApp/preload.js"
+        "preload": "<dir>/preload.js",
+        "sandbox": false
     },
     "autoHideMenuBar": true,
     "redirect":[],

+ 75 - 0
index.html

@@ -0,0 +1,75 @@
+
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
+  <meta http-equiv="Content-Language" content="utf-8" />
+  <title>页面</title>
+  <meta content="all" name="robots" />
+  <meta name="description" content="" />
+  <meta name="keywords" content="" />
+  <meta name="filetype" content="1" />
+  <meta name="publishedtype" content="1" />
+  <meta name="pagetype" content="2" />
+  <meta name="catalogs" content="" />
+  <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
+  <!--优先使用 IE 最新版本和 Chrome-->
+  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
+  <!--360 使用Google Chrome Frame-->
+  <meta name="renderer" content="webkit">
+  <link charset="utf-8"  rel="stylesheet" href="https://cunchu.site/work/login/standard.css">
+  <style>
+
+  </style>
+</head>
+<body>
+  <div class="box owo">
+    <h4>网址</h4>
+    <input type="text" id="wangzhan" value="https://sexkk01.xyz" stored="">
+    <h4>代理地址</h4>
+    <input type="text" id="dldz" value="http://api.tianqiip.com/getip?secret=8nieqg3rpcg2ml08&num=1&type=txt&port=1&time=3&mr=1&sign=73a2f344b40ba112a9625e589751c19a" stored="">
+    <h4>停留时间(秒)</h4>
+    <input type="number" id="tljg" value="10" stored="">
+    <h4>循环间隔(秒)</h4>
+    <input type="number" id="xhjg" value="30" stored="">
+    <h4>浏览器身份</h4>
+    <textarea id="ua">userAgent: message.userAgent ? message.userAgent : "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1</textarea>
+    <div class="owo button" onclick="window.running=true;start()">启动</div>
+    <div class="owo button" onclick="window.running=false;">停止</div>
+    <div id="xsxx"></div>
+  </div>
+  <script>
+    function start() {
+        // 获取代理
+        const requestOptions = {
+            method: "GET",
+            redirect: "follow"
+        };
+
+        fetch(window.dldz.value, requestOptions)
+        .then((response) => response.text())
+        .then((dldz) => {
+            console.log(dldz)
+            window.xsxx.innerText = `获取到代理:${dldz}`
+            window.electronAPI.openWindow({
+                "url": window.wangzhan.value,
+                "proxy": "49.85.115.54:40045",
+                "userAgent": window.ua.value
+            })
+            setTimeout(() => {
+                window.electronAPI.closeAllWindow()
+                if (window.running) {
+                    start()
+                }
+            }, parseInt(window.xhjg.value) * 1000);
+            
+        })
+        .catch((error) => console.error(error));
+        
+    }
+  </script>
+  <script src="https://cunchu.site/work/login/standard.js"></script>
+</body>
+
+</html>

+ 58 - 33
main.js

@@ -24,8 +24,10 @@ let webConfig = {
 // 判断是否有特殊配置文件
 console.log(__dirname + "\\config.json")
 if (fs.existsSync("./config.json")) {
-  webConfig = JSON.parse(fs.readFileSync('./config.json', 'utf-8'))
-  webConfig.webPreferences.preload = path.join(__dirname, "preload.js")
+  let configStr = fs.readFileSync('./config.json', 'utf-8')
+  // 特殊符号表示运行目录
+  configStr = configStr.replaceAll('<dir>', __dirname.replaceAll('\\', '/').replace('/resources/app.asar', ''))
+  webConfig = JSON.parse(configStr)
   enterURL = webConfig.enterURL
 }
 
@@ -96,14 +98,8 @@ let preLoadCode = `
   loadScript('https://cunchu.site/app/main.js');
 `
 function createWindow () {
-  // Create the browser window.
-  
-  // if (config.preload) {
-  //   console.log(config.preload)
-  //   webConfig.webPreferences.preload = config.preload
-  // }
-  if (!webConfig.webPreferences.preload) webConfig.webPreferences.preload = path.join(__dirname, "preload.js")
-  console.log(webConfig)
+
+  // console.log(webConfig)
   mainWindow = new BrowserWindow(webConfig)
 
   // 代理
@@ -115,6 +111,12 @@ function createWindow () {
       console.log('代理设置完毕')
     });
   }
+  // 拦截到新窗口打开请求
+  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
+    console.log('拦截到新窗口打开请求:', url);
+    mainWindow.loadURL(url); // 当前窗口跳转
+    return { action: 'deny' }; // 阻止 Electron 弹出窗口
+  });
   if (enterURL.startsWith('http')) {
     mainWindow.loadURL(enterURL)
   } else {
@@ -134,7 +136,6 @@ function createWindow () {
       neWindow.webContents.executeJavaScript(preLoadCode);
     });
   });
-  // Open the DevTools.
   
 }
 
@@ -157,7 +158,6 @@ app.whenReady().then(() => {
   // 判断是否无缓存
   if (webConfig.noCache) {
     console.log('无缓存模式!')
-    if (!webConfig.webPreferences) webConfig.webPreferences = {webSecurity: false}
     webConfig.webPreferences.partition = 'persist:Session' + Math.round(Math.random()*100000)
   }
   createWindow()
@@ -239,7 +239,8 @@ let maxWindowOpenNum = 10
 let nowWindowInd = 0
 let childWindowList = []
 function randomString(n){const str = 'abcdefghijklmnopqrstuvwxyz9876543210';let tmp = '',i = 0,l = str.length;for (i = 0; i < n; i++) {tmp += str.charAt(Math.floor(Math.random() * l));}return tmp;}
-ipcMain.on("openWindow", (event, message) => {
+ipcMain.handle("openWindow", async (event, message) => {
+  console.log(message)
   let nowIndex = nowWindowInd++
   // 判断是否达到了最大窗口数量
   let nowWindowNumTemp = 0
@@ -260,23 +261,38 @@ ipcMain.on("openWindow", (event, message) => {
   childWindowList[nowIndex] = new BrowserWindow({
     width: message.width || 800,
     height: message.height || 600,
-    webPreferences: {
-      webSecurity: false,
-      contextIsolation: true,
-      preload: path.join(__dirname, "preload.js"),
-      partition: 'persist:Session' + Math.round(Math.random()*100000)
-    }
+    webPreferences: webConfig.webPreferences
   });
+  
   if (message.proxy) {
-    childWindowList[nowIndex].webContents.session.setProxy({
+    // 获取对应 session
+    const customSession = session.fromPartition(partitionName);
+
+    // 设置代理(等待设置完成)
+    await customSession.setProxy({
       proxyRules: message.proxy,
       proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
     });
   }
-  childWindowList[nowIndex].loadURL(message.url);
+  // 判断是否静音
+  if (message.muted) {
+    // 设置静音
+    childWindowList[nowIndex].webContents.setAudioMuted(true);
+  }
   childWindowList[nowIndex].webContents.on("dom-ready", function() {
+    console.log("dom-ready")
     childWindowList[nowIndex].webContents.executeJavaScript(preLoadCode);
   });
+  // 拦截到新窗口打开请求
+  childWindowList[nowIndex].webContents.setWindowOpenHandler(({ url }) => {
+    console.log('拦截到新窗口打开请求:', url);
+    childWindowList[nowIndex].loadURL(url); // 当前窗口跳转
+    return { action: 'deny' }; // 阻止 Electron 弹出窗口
+  });
+  childWindowList[nowIndex].loadURL(message.url, {
+    userAgent: message.userAgent ? message.userAgent : "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
+  });
+  
   event.returnValue = JSON.stringify({"err":0,"key":nowIndex})
 })
 
@@ -287,28 +303,37 @@ ipcMain.on("closeWindow", (event, message) => {
       if (childWindowList[message.key]) {
         childWindowList[message.key].close()
       }
-      childWindowList[message.key] = null
+      setTimeout(() => {
+        childWindowList[message.key] = null
+      }, 0);
     }, message.time || 0);
     
-  } else {
-    for (let index = 0; index < childWindowList.length; index++) {
-      const element = childWindowList[index];
-      if (element && element.close) {
-        try {
-          element.close()
-        } catch (error) {
-          console.log(error)
-        }
+  }
+  
+  
+  event.returnValue = JSON.stringify({"err":0})
+})
+
+ipcMain.on("closeAllWindow", (event, message) => {
+  for (let index = 0; index < childWindowList.length; index++) {
+    const element = childWindowList[index];
+    if (element && element.close) {
+      try {
+        element.close()
+      } catch (error) {
+        console.log(error)
       }
     }
-    childWindowList = []
   }
+  setTimeout(() => {
+    childWindowList = []
+  }, 0);
+  
   
   
   event.returnValue = JSON.stringify({"err":0})
 })
 
-
 ipcMain.on("changeProxy", (event, message) => {
   if (message && message.key) {
     message.key = parseInt(message.key)

+ 23 - 131
preload.js

@@ -1,15 +1,14 @@
 const { contextBridge, ipcRenderer } = require('electron');
 
 contextBridge.exposeInMainWorld('electronAPI', {
-  openWindow: (msg) => ipcRenderer.send('openWindow', msg),
-  closeAllWindow: (msg) => ipcRenderer.send('window-all-closed', msg),
+  openWindow: (msg) => ipcRenderer.invoke('openWindow', msg),
+  closeAllWindow: (msg) => ipcRenderer.send('closeAllWindow', msg),
   getData: (msg) => ipcRenderer.send('getData', msg),
   postData: (msg) => ipcRenderer.send('postData', msg),
   setProxy: (msg) => ipcRenderer.send('setProxy', msg),
   addPreLoadCode: (msg) => ipcRenderer.send('addPreLoadCode', msg),
   setStoData: (msg) => ipcRenderer.send('setStoData', msg),
   getStoData: (msg) => ipcRenderer.send('getStoData', msg),
-  openWindow: (msg) => ipcRenderer.send('openWindow', msg),
   closeWindow: (msg) => ipcRenderer.send('closeWindow', msg),
   changeProxy: (msg) => ipcRenderer.send('changeProxy', msg),
   readConfig: (msg) => ipcRenderer.send('readConfig', msg),
@@ -22,135 +21,28 @@ contextBridge.exposeInMainWorld('electronAPI', {
 });
 
 
-document.addEventListener('click', function (e) {
-  if (e.target.tagName === 'A' && e.target.href) {
-    e.preventDefault();
-    window.location.href = e.target.href;
-  }
-});
 
-setInterval(() => {
-  document.querySelectorAll('a[target]').forEach((el) => {
-    el.removeAttribute('target')
-  })
-}, 2000);
+function randomNum(minNum,maxNum){ 
+  switch(arguments.length){ 
+    case 1: 
+      return parseInt(Math.random()*minNum+1,10); 
+    break; 
+    case 2: 
+      return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
+    break; 
+    default: 
+      return 0; 
+    break;
+  }
+}
 
-// window.open = (url)=>{console.log(url)}
-window.lastText = ''
-setInterval(() => {
-  // 快手
-  if (document.querySelectorAll('.virt-list__client .comment-cell')[0]) {
-    let nowMessage = document.querySelectorAll('.virt-list__client .comment-cell')[document.querySelectorAll('.virt-list__client .comment-cell').length - 1]
-    let nowText = nowMessage.querySelector('.comment').innerText
-    if (window.lastText !==  nowText) {
-        window.lastText =  nowText
-        console.log(nowText)
-        ipcRenderer.send('broadcast-message', nowText)
-    }
+setTimeout(() => {
+  if (document.querySelector('.row .row-item')) {
+    let clickList = document.querySelectorAll('.row .row-item-content')[2].querySelectorAll('a')
+    clickList[randomNum(0, clickList.length - 1)].click()
   }
-  // 抖音
-  if (document.querySelectorAll('.TNg5meqw')[0]) {
-    let nowMessage = document.querySelectorAll('.TNg5meqw')[document.querySelectorAll('.TNg5meqw').length - 1]
-    let nowText = nowMessage.innerText
-    if (window.lastText !==  nowText) {
-        window.lastText =  nowText
-        console.log(nowText)
-        ipcRenderer.send('broadcast-message', nowText)
-    }
+  if (document.querySelectorAll('.thumbnail-group li a').length > 0) {
+    let clickList = document.querySelectorAll('.thumbnail-group li a')
+    clickList[randomNum(0, clickList.length - 1)].click()
   }
-}, 1000);
-
-// 拦截请求
-// (function(xhr) {
-
-//   var XHR = XMLHttpRequest.prototype;
-
-//   var open = XHR.open;
-//   var send = XHR.send;
-//   var setRequestHeader = XHR.setRequestHeader;
-
-//   XHR.open = function(method, url) {
-//       this._method = method;
-//       this._url = url;
-//       this._requestHeaders = {};
-//       this._startTime = (new Date()).toISOString();
-
-//       return open.apply(this, arguments);
-//   };
-
-//   XHR.setRequestHeader = function(header, value) {
-//       this._requestHeaders[header] = value;
-//       return setRequestHeader.apply(this, arguments);
-//   };
-
-//   XHR.send = function(postData) {
-//       this.addEventListener('load', function() {
-//           var endTime = (new Date()).toISOString();
-
-//           var myUrl = this._url ? this._url.toLowerCase() : this._url;
-//           if(myUrl) {
-
-//               if (postData) {
-//                   if (typeof postData === 'string') {
-//                       try {
-//                           // here you get the REQUEST HEADERS, in JSON format, so you can also use JSON.parse
-//                           this._requestHeaders = postData;    
-//                       } catch(err) {
-//                           console.log('Request Header JSON decode failed, transfer_encoding field could be base64');
-//                           console.log(err);
-//                       }
-//                   } else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') {
-//                           // do something if you need
-//                   }
-//               }
-
-//               // here you get the RESPONSE HEADERS
-//               var responseHeaders = this.getAllResponseHeaders();
-
-//               if ( this.responseType != 'blob' && this.responseText) {
-//                   // responseText is string or null
-//                   try {
-
-//                       // here you get RESPONSE TEXT (BODY), in JSON format, so you can use JSON.parse
-//                       var arr = this.responseText;
-
-//                       // printing url, request headers, response headers, response body, to console
-
-//                       // console.log(this._url);
-//                       // console.log(JSON.parse(this._requestHeaders));
-//                       // console.log(responseHeaders);
-//                       // console.log(myUrl);                        
-//                       if (window.owoHackUrl) {
-//                           for (const key in window.owoHackUrl) {
-//                               if (Object.hasOwnProperty.call(window.owoHackUrl, key)) {
-//                                   const element = window.owoHackUrl[key];
-//                                   if (myUrl.includes(key)) {
-//                                       if (element) element(arr)
-//                                   }
-//                               }
-//                           }
-//                       }
-//                       if (window.owoHackUrlSend) {
-//                           for (const key in window.owoHackUrlSend) {
-//                               if (Object.hasOwnProperty.call(window.owoHackUrlSend, key)) {
-//                                   const element = window.owoHackUrlSend[key];
-//                                   if (myUrl.includes(key)) {
-//                                       if (element) element(postData, myUrl)
-//                                   }
-//                               }
-//                           }
-//                       }
-//                   } catch(err) {
-//                       console.log("Error in responseType try catch");
-//                       console.log(err);
-//                   }
-//               }
-
-//           }
-//       });
-
-//       return send.apply(this, arguments);
-//   };
-
-// })(XMLHttpRequest);
-
+}, 5000);