Browse Source

调整验证函数

torsen
453530270@qq.com 1 year ago
parent
commit
73a7b393e5
  1. 171
      douyin/background.js

171
douyin/background.js

@ -8,13 +8,13 @@ chrome.runtime.onInstalled.addListener(() => {
async function checkProxyAvailability(proxyConfig) {
return new Promise((resolve) => {
const timeoutDuration = 10000; // 增加超时时间到10秒
console.log(`正在测试代理 ${proxyConfig.host}:${proxyConfig.port} 的可用性...`);
// 使用 XMLHttpRequest 来测试代理
const xhr = new XMLHttpRequest();
xhr.timeout = timeoutDuration;
// 设置超时处理
const timeoutHandler = setTimeout(() => {
xhr.abort();
@ -22,7 +22,7 @@ async function checkProxyAvailability(proxyConfig) {
resolve(false);
}, timeoutDuration);
xhr.onreadystatechange = function() {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
clearTimeout(timeoutHandler);
if (xhr.status === 200) {
@ -35,7 +35,7 @@ async function checkProxyAvailability(proxyConfig) {
}
};
xhr.onerror = function() {
xhr.onerror = function () {
clearTimeout(timeoutHandler);
console.log(`代理 ${proxyConfig.host}:${proxyConfig.port} 连接错误`);
resolve(false);
@ -68,11 +68,13 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
windowProxyMap.set(windowId, proxyConfig);
// 设置认证监听器
const authHandler = function(details) {
const authHandler = function (details) {
console.log("=========PROXY CONFIG===========",proxyConfig)
return {
authCredentials: {
username: proxyConfig.username,
password: proxyConfig.password
username: "hwfq28m43",
password: "YW29ABi6"
}
};
};
@ -80,11 +82,17 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
// 移除之前的监听器(如果存在)
try {
chrome.webRequest.onAuthRequired.removeListener(authHandler);
} catch (e) {}
} catch (e) { }
// 添加新的监听器
chrome.webRequest.onAuthRequired.addListener(
authHandler,
// authHandler,
function(details,callbackFn){
console.log("onAuthRequired!", details, callbackFn);
callbackFn({
authCredentials: {username: "hwfq28m43", password: "YW29ABi6"}
});
},
{ urls: ["<all_urls>"] },
["asyncBlocking"]
);
@ -98,7 +106,16 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
scheme: "http",
host: proxyConfig.host,
port: parseInt(proxyConfig.port)
},
httpsProxy:{
// 添加 HTTPS 代理规则
scheme: "http",
host: proxyConfig.host,
port: parseInt(proxyConfig.port),
username: proxyConfig.username,
password: proxyConfig.password
}
}
},
scope: "regular"
@ -107,7 +124,7 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
// 设置代理
chrome.proxy.settings.set(
config,
function() {
function () {
if (chrome.runtime.lastError) {
console.error('设置代理失败:', chrome.runtime.lastError);
callback(chrome.runtime.lastError);
@ -115,17 +132,17 @@ function setProxyForWindow(proxyConfig, windowId, callback) {
}
console.log(`窗口 ${windowId} 代理设置成功`);
// 刷新标签页
chrome.tabs.query({ windowId: windowId }, function(tabs) {
chrome.tabs.query({ windowId: windowId }, function (tabs) {
if (tabs.length === 0) {
callback(null, true);
return;
}
let refreshedCount = 0;
tabs.forEach(function(tab) {
chrome.tabs.reload(tab.id, { bypassCache: true }, function() {
tabs.forEach(function (tab) {
chrome.tabs.reload(tab.id, { bypassCache: true }, function () {
refreshedCount++;
if (refreshedCount === tabs.length) {
callback(null, true);
@ -142,10 +159,10 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'checkIncognitoWindows') {
chrome.windows.getAll({ populate: true }, (windows) => {
console.log('获取到所有窗口数量:', windows.length);
const incognitoWindows = windows.filter(w => w.incognito);
console.log('找到无痕窗口数量:', incognitoWindows.length);
const windowDetails = incognitoWindows.map(w => ({
id: w.id,
type: w.type,
@ -153,9 +170,9 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
tabCount: w.tabs ? w.tabs.length : 0,
firstTabUrl: w.tabs && w.tabs[0] ? w.tabs[0].url : 'no tabs'
}));
console.log('无痕窗口详情:', windowDetails);
sendResponse({
count: incognitoWindows.length,
windows: windowDetails,
@ -170,14 +187,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
chrome.windows.create({
incognito: true,
url: "https://www.douyin.com"
}, function(window) {
}, function (window) {
console.log('抖音无痕窗口已打开');
});
} else if (request.action === 'openLiveIncognito') {
chrome.windows.create({
incognito: true,
url: request.url
}, function(window) {
}, function (window) {
console.log('直播无痕窗口已打开');
});
}
@ -195,34 +212,34 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
},
body: JSON.stringify(loginData)
})
.then(response => response.json())
.then(data => {
console.log('登录结果:', data);
if (data.status === 200) {
sendResponse({ status: 'success' });
chrome.storage.local.set({ loginStatus: true });
chrome.storage.local.set({ loginInfo: loginData });
chrome.storage.local.set({ loginTime: new Date().toLocaleString() });
chrome.storage.local.set({ loginToken: data.token });
chrome.cookies.set({
url: 'https://douyin.xingtongworld.com',
name: 'sessionid',
value: data.token,
domain: 'douyin.xingtongworld.com'
});
} else {
sendResponse({ status: 'error', message: '登录失败:' + (data.message || '未知错误') });
}
})
.catch(error => {
console.error('登录请求出错:', error);
sendResponse({ status: 'error', message: '登录请出错,请检查网络连接或稍后重试。' });
});
.then(response => response.json())
.then(data => {
console.log('登录结果:', data);
if (data.status === 200) {
sendResponse({ status: 'success' });
chrome.storage.local.set({ loginStatus: true });
chrome.storage.local.set({ loginInfo: loginData });
chrome.storage.local.set({ loginTime: new Date().toLocaleString() });
chrome.storage.local.set({ loginToken: data.token });
chrome.cookies.set({
url: 'https://douyin.xingtongworld.com',
name: 'sessionid',
value: data.token,
domain: 'douyin.xingtongworld.com'
});
} else {
sendResponse({ status: 'error', message: '登录失败:' + (data.message || '未知错误') });
}
})
.catch(error => {
console.error('登录请求出错:', error);
sendResponse({ status: 'error', message: '登录请出错,请检查网络连接或稍后重试。' });
});
}
if (request.action === 'checkStatus') {
let status = '正常';
sendResponse({status: status});
sendResponse({ status: status });
}
if (request.action === 'openLiveWithProxy') {
@ -264,8 +281,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('可用代理列表:', proxyList);
if (proxyList.length === 0) {
sendResponse({
success: false,
sendResponse({
success: false,
error: '没有可用的代理'
});
return;
@ -283,7 +300,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
}
const window = incognitoWindows[currentIndex];
// 检查窗口是否已经有代理设置
const existingProxy = windowProxyMap.get(window.id);
if (existingProxy) {
@ -301,7 +318,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// 使用循环方式获取代理配置
const proxyIndex = currentIndex % proxyList.length;
const proxy = proxyList[proxyIndex];
if (!proxy || !proxy.host || !proxy.port) {
errors.push(`代理配置无效: ${JSON.stringify(proxy)}`);
completedCount++;
@ -345,12 +362,12 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
function checkComplete() {
if (completedCount === incognitoWindows.length) {
if (errors.length > 0) {
sendResponse({
success: false,
error: errors.join('\n')
sendResponse({
success: false,
error: errors.join('\n')
});
} else {
sendResponse({
sendResponse({
success: true,
message: `已为 ${incognitoWindows.length} 个无痕窗口设置代理`
});
@ -364,12 +381,13 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
return true;
}
// 清除代理信息
if (request.action === 'clearProxy') {
try {
// 清除代理设置
chrome.proxy.settings.clear(
{ scope: "regular" },
async function() {
async function () {
if (chrome.runtime.lastError) {
console.error('清除代理设置失败:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
@ -381,8 +399,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
try {
// 获取所有窗口
const windows = await new Promise((resolve) => {
chrome.windows.getAll({
populate: true
chrome.windows.getAll({
populate: true
}, resolve);
});
@ -436,15 +454,15 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
}
}
sendResponse({
sendResponse({
success: true,
message: '已清除所有代理设置、认证缓存并刷新标签页'
});
} catch (error) {
console.error('刷新标签页时出错:', error);
sendResponse({
success: false,
error: '清除代理成功但刷新标签页失败: ' + error.message
sendResponse({
success: false,
error: '清除代理成功但刷新标签页失败: ' + error.message
});
}
}
@ -456,11 +474,12 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
return true;
}
// 当前代理
if (request.action === 'getCurrentProxy') {
try {
const windowId = request.windowId;
const proxyConfig = windowProxyMap.get(windowId);
if (proxyConfig) {
sendResponse({
success: true,
@ -488,13 +507,14 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
}
chrome.webRequest.onCompleted.addListener(
function(details) {
function (details) {
console.log("请求完成:", details);
},
{urls: ["<all_urls>"]}
{ urls: ["<all_urls>"] }
);
});
// 新窗口监听
chrome.windows.onCreated.addListener((window) => {
console.log('新窗口创:', {
id: window.id,
@ -507,6 +527,7 @@ chrome.windows.onCreated.addListener((window) => {
});
});
// 新标签监听
chrome.tabs.onCreated.addListener((tab) => {
console.log('新标签创建:', {
id: tab.id,
@ -517,7 +538,7 @@ chrome.tabs.onCreated.addListener((tab) => {
// 修改错误监听器,添加更多需要忽略的误类型
chrome.webRequest.onErrorOccurred.addListener(
function(details) {
function (details) {
// 扩展需要忽略的错误类型列表
const ignoredErrors = [
'net::ERR_ABORTED', // 请求中断
@ -540,10 +561,10 @@ chrome.webRequest.onErrorOccurred.addListener(
'other' // 其他资源
];
if (details.error &&
!ignoredErrors.includes(details.error) &&
!ignoredResourceTypes.includes(details.type)) {
if (details.error &&
!ignoredErrors.includes(details.error) &&
!ignoredResourceTypes.includes(details.type)) {
// 只记录重要的错误
const errorInfo = {
错误类型: details.error,
@ -554,26 +575,26 @@ chrome.webRequest.onErrorOccurred.addListener(
};
// 如果是代理相关错误,添加更多信息
if (details.error.toLowerCase().includes('proxy') ||
details.error.toLowerCase().includes('connection_refused')) {
if (details.error.toLowerCase().includes('proxy') ||
details.error.toLowerCase().includes('connection_refused')) {
errorInfo.代理错误 = true;
errorInfo.IP地址 = details.ip || '未知';
console.error('代理相关错误:\n' +
console.error('代理相关错误:\n' +
Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`)
.join('\n')
);
} else if (details.error.toLowerCase().includes('cert')) {
// 证书相关错误
console.warn('证书相关错误:\n' +
console.warn('证书相关错误:\n' +
Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`)
.join('\n')
);
} else {
// 其他重要错误
console.error('重要网络错误:\n' +
console.error('重要网络错误:\n' +
Object.entries(errorInfo)
.map(([key, value]) => `${key}: ${value}`)
.join('\n')
@ -581,7 +602,7 @@ chrome.webRequest.onErrorOccurred.addListener(
}
}
},
{urls: ["<all_urls>"]}
{ urls: ["<all_urls>"] }
);
chrome.windows.onRemoved.addListener((windowId) => {
@ -620,7 +641,7 @@ chrome.windows.onRemoved.addListener((windowId) => {
// 添加证书错误处理
chrome.webRequest.onErrorOccurred.addListener(
function(details) {
function (details) {
if (details.error && details.error.includes('ERR_CERT')) {
console.log('忽略证书错误:', details.url);
return { cancel: false };

Loading…
Cancel
Save