Compare commits

...

6 Commits

Author SHA1 Message Date
7164dc3ed5 1 2026-03-26 20:56:06 +08:00
张成
6200fcc66f 1 2026-03-25 15:55:55 +08:00
张成
7ba462aedd 1 2026-03-20 10:55:55 +08:00
张成
873fd436b1 1 2026-03-19 18:44:18 +08:00
张成
66df49a7c3 1 2026-03-19 18:36:41 +08:00
张成
a776873477 1 2026-03-19 17:54:30 +08:00
25 changed files with 1430 additions and 904 deletions

View File

@@ -0,0 +1,163 @@
# 模块化重构说明
## 🎯 重构目标
使用现代 ES6 模块化方式,将分散的独立函数整合到统一的导出文件中,提供更友好的开发体验。
## 📁 新的项目结构
```
src/
├── libs/
│ ├── index.js # 统一导出所有库函数
│ ├── action_response.js
│ ├── tabs.js
│ └── action_meta.js
├── actions/
│ ├── index.js # 统一导出所有动作
│ ├── amazon.js
│ └── amazon_tool.js
├── background/
│ └── index.js # 使用新的导入方式
└── examples/
└── usage_example.js # 使用示例
```
## 🚀 使用方式
### 1. 命名导入(推荐)
```javascript
import {
ok_response,
fail_response,
create_tab_task,
getAllActionsMeta,
getActionByName
} from './libs/index.js';
```
### 2. 默认导入使用对象
```javascript
import Libs from './libs/index.js';
import Actions from './actions/index.js';
// 使用
const response = Libs.response.ok({ data: 'success' });
const task = Libs.tabs.createTask('https://example.com');
const actions = Actions.amazon;
```
### 3. 混合使用
```javascript
// 直接需要的函数用命名导入
import { ok_response, create_tab_task } from './libs/index.js';
// 复杂对象用默认导入
import Actions from './actions/index.js';
const action = getActionByName('amazon_search_list');
```
## 📦 统一导出内容
### libs/index.js
```javascript
// 响应处理
export {
ok_response,
fail_response,
response_code,
guard_sync
} from './action_response.js';
// Tab 操作
export {
raw_execute_script,
inject_file,
ensure_injected,
execute_script,
open_tab,
close_tab,
create_tab_task
} from './tabs.js';
// 元数据处理
export {
bind_action_meta
} from './action_meta.js';
// 便捷对象
export const Libs = {
response: { ok: ok_response, fail: fail_response, ... },
tabs: { open: open_tab, close: close_tab, ... },
meta: { bindAction: bind_action_meta }
};
```
### actions/index.js
```javascript
// 导出所有动作
export { amazon_actions } from './amazon.js';
// 导出工具函数
export {
injected_amazon_validate_captcha_continue,
run_amazon_pdp_action,
// ... 其他工具函数
} from './amazon_tool.js';
// 便捷函数
export function getAllActionsMeta() { ... }
export function getActionByName(name) { ... }
// 便捷对象
export const Actions = {
amazon: amazon_actions,
amazonTools: { ... }
};
```
## ✅ 优势
1. **统一入口** - 不需要记住具体的文件路径
2. **灵活导入** - 支持命名导入、默认导入、混合导入
3. **便于维护** - 集中管理所有导出
4. **向后兼容** - 保持原有功能不变
5. **现代语法** - 使用最新的 ES6 模块特性
## 🔄 迁移指南
### 旧方式
```javascript
import { create_tab_task } from '../libs/tabs.js';
import { ok_response } from '../libs/action_response.js';
import { amazon_actions } from '../actions/amazon.js';
```
### 新方式
```javascript
import { create_tab_task, ok_response, amazon_actions } from '../libs/index.js';
// 或者
import { create_tab_task, ok_response } from '../libs/index.js';
import { amazon_actions } from '../actions/index.js';
```
## 🎨 最佳实践
1. **简单函数** - 使用命名导入
2. **复杂对象** - 使用默认导入
3. **类型安全** - 配合 TypeScript 使用
4. **按需导入** - 只导入需要的功能
5. **统一风格** - 在一个项目中保持一致的导入风格
## 🔧 开发建议
- 新增功能时,优先添加到对应的 `index.js` 文件
- 保持导出名称的一致性和可读性
- 使用 JSDoc 注释提高代码可读性
- 定期检查和优化导出结构

View File

@@ -1,358 +1,304 @@
// Amazonaction编排逻辑放这里注入函数放 amazon_tool.js
import { create_tab_task } from '../libs/tabs.js';
import { fail_response, ok_response, response_code } from '../libs/action_response.js';
import { create_tab_task, ok_response, fail_response, guard_sync, response_code, sleep_ms, get_tab_url } from '../libs/index.js';
import {
injected_amazon_homepage_search,
injected_amazon_validate_captcha_continue,
injected_amazon_product_detail,
injected_amazon_product_reviews,
injected_amazon_search_list,
injected_amazon_switch_language,
injected_amazon_validate_captcha_continue,
injected_amazon_search_list,
injected_amazon_homepage_search,
injected_detect_captcha_page,
normalize_product_url,
pick_first_script_result,
try_solve_amazon_validate_captcha,
wait_until_search_list_url,
} from './amazon_tool.js';
const AMAZON_HOME_FOR_LANG = 'https://www.amazon.com/customer-preferences/edit?ie=UTF8&preferencesReturnUrl=%2F&ref_=topnav_lang_ais&language=zh_CN&currency=HKD';
const AMAZON_ZH_HOME_URL = 'https://www.amazon.com/-/zh/ref=nav_logo';
const AMAZON_HOME_FOR_LANG =
'https://www.amazon.com/customer-preferences/edit?ie=UTF8&preferencesReturnUrl=%2F&ref_=topnav_lang_ais&language=zh_CN&currency=HKD';
export function amazon_search_list(data, sendResponse) {
return new Promise((resolve, reject) => {
const category_keyword = data && data.category_keyword ? String(data.category_keyword).trim() : '';
const sort_by = data && data.sort_by ? String(data.sort_by).trim() : '';
const keep_tab_open = data && data.keep_tab_open === true;
const limit = (() => {
const n = data && Object.prototype.hasOwnProperty.call(data, 'limit') ? Number(data.limit) : 100;
if (!Number.isFinite(n)) return 100;
return Math.max(1, Math.min(200, Math.floor(n)));
})();
const keyword = category_keyword || 'picnic bag';
// ──────────── 公共工具 ────────────
const sort_map = {
featured: 'relevanceblender',
review: 'review-rank',
newest: 'date-desc-rank',
price_asc: 'price-asc-rank',
price_desc: 'price-desc-rank',
bestseller: 'exact-aware-popularity-rank',
};
const sort_s = Object.prototype.hasOwnProperty.call(sort_map, sort_by) ? sort_map[sort_by] : '';
const send_action = (action, payload) => {
if (typeof sendResponse === 'function') {
sendResponse({ action, data: payload });
sendResponse.log && sendResponse.log(payload);
}
};
const tab_task = create_tab_task(AMAZON_ZH_HOME_URL)
.set_latest(false)
.set_bounds({ top: 20, left: 20, width: 1440, height: 900 })
.set_target('__amazon_search_list');
let url = AMAZON_ZH_HOME_URL;
tab_task.open_async()
.then((tab) => {
tab.on_update_complete(async () => {
await tab.execute_script(injected_amazon_search_list, [{ category_keyword, sort_by, debug: true }], 'document_idle');
await try_solve_amazon_validate_captcha(tab, 3);
const home_ret = await tab.execute_script(injected_amazon_homepage_search, [{ keyword }], 'document_idle');
const home_ok = Array.isArray(home_ret) ? home_ret[0] : home_ret;
if (!home_ok || !home_ok.ok) {
throw new Error((home_ok && home_ok.error) || '首页搜索提交失败');
}
url = await wait_until_search_list_url(tab.id, 45000);
await tab.wait_complete();
if (sort_s) {
const u = new URL(url);
u.searchParams.set('s', sort_s);
url = u.toString();
await tab.navigate(url);
await tab.wait_complete();
}
const unique_map = new Map();
let next_url = url;
for (let page = 1; page <= 10 && unique_map.size < limit; page += 1) {
if (page > 1) {
await tab.navigate(next_url);
await tab.wait_complete();
}
const injected_result_list = await tab.execute_script(
injected_amazon_search_list,
[{ url: next_url, category_keyword, sort_by }],
'document_idle',
);
const injected_result = Array.isArray(injected_result_list) ? injected_result_list[0] : null;
const items = injected_result && Array.isArray(injected_result.items) ? injected_result.items : [];
items.forEach((it) => {
const k = it && (it.asin || it.url) ? String(it.asin || it.url) : null;
if (!k) return;
if (!unique_map.has(k)) unique_map.set(k, it);
});
if (unique_map.size >= limit) break;
next_url = injected_result && injected_result.next_url ? String(injected_result.next_url) : null;
if (!next_url) break;
}
const list_result = { stage: 'list', limit, total: unique_map.size, items: Array.from(unique_map.values()).slice(0, limit) };
const result = ok_response({ tab_id: tab.id, url, category_keyword, sort_by: sort_by || 'featured', limit, result: list_result });
send_action('amazon_search_list', result);
resolve({ tab_id: tab.id, url, category_keyword, sort_by: sort_by || 'featured', limit, result: list_result });
if (!keep_tab_open) {
tab.remove(0);
}
}, {
once: true,
on_error: (err) => {
send_action('amazon_search_list', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: url || AMAZON_ZH_HOME_URL,
}));
reject(err);
if (!keep_tab_open) {
tab.remove(0);
}
},
});
})
.catch((err) => {
send_action('amazon_search_list', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: url || AMAZON_ZH_HOME_URL,
}));
reject(err);
});
});
}
amazon_search_list.desc = 'Amazon 搜索列表:先打开中文首页,搜索框输入类目并搜索,再分页抓取';
amazon_search_list.params = {
category_keyword: { type: 'string', desc: '类目关键词(在首页搜索框输入后点搜索,进入列表再抓)', default: '野餐包' },
sort_by: { type: 'string', desc: '排序方式featured / price_asc / price_desc / review / newest / bestseller', default: 'featured' },
limit: { type: 'number', desc: '抓取数量上限(默认 100最大 200', default: 100 },
keep_tab_open: { type: 'boolean', desc: '调试用:不自动关闭窗口,方便手动刷新观察轨迹', default: false },
const create_send_action = (sendResponse) => (action_name, response) => {
sendResponse({ action: action_name, ...response });
};
export function amazon_set_language(data, sendResponse) {
return new Promise((resolve, reject) => {
const mapping = {
EN: 'en_US',
ES: 'es_US',
AR: 'ar_AE',
DE: 'de_DE',
HE: 'he_IL',
KO: 'ko_KR',
PT: 'pt_BR',
ZH_CN: 'zh_CN',
ZH_TW: 'zh_TW',
};
const raw_lang = data && data.lang != null ? String(data.lang).trim().toUpperCase() : 'ZH_CN';
const code = Object.prototype.hasOwnProperty.call(mapping, raw_lang) ? raw_lang : 'ZH_CN';
const send_action = (action, payload) => {
if (typeof sendResponse === 'function') {
sendResponse({ action, data: payload });
sendResponse.log && sendResponse.log(payload);
}
};
const tab_task = create_tab_task(AMAZON_HOME_FOR_LANG)
.set_latest(false)
.set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
tab_task.open_async()
.then((tab) => {
tab.on_update_complete(async () => {
// 首次 complete 也会触发:在回调里完成注入与结果采集
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
const raw = await tab.execute_script(injected_amazon_switch_language, [{ lang: code }], 'document_idle');
const inj = Array.isArray(raw) ? raw[0] : raw;
if (!inj || !inj.ok) {
throw new Error((inj && inj.error) || 'switch_language_failed');
}
const final_url = await new Promise((res, rej) => {
chrome.tabs.get(tab.id, (tt) => {
if (chrome.runtime.lastError) return rej(new Error(chrome.runtime.lastError.message));
res(tt && tt.url ? tt.url : '');
});
});
const result = ok_response({ tab_id: tab.id, lang: inj.lang, url: final_url });
send_action('amazon_set_language', result);
resolve({ tab_id: tab.id, lang: inj.lang, url: final_url });
tab.remove(0);
}, {
once: true,
on_error: (err) => {
send_action('amazon_set_language', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: AMAZON_HOME_FOR_LANG,
}));
reject(err);
},
});
})
.catch((err) => {
send_action('amazon_set_language', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: AMAZON_HOME_FOR_LANG,
}));
reject(err);
});
});
}
amazon_set_language.desc =
'Amazon 顶栏语言:打开美站首页,悬停语言区后点击列表项(#switch-lang切换购物界面语言';
amazon_set_language.params = {
lang: { type: 'string', desc: 'EN / ES / AR / DE / HE / KO / PT / ZH_CN(默认) / ZH_TW', default: 'ZH_CN' },
const SORT_MAP = {
featured: 'relevanceblender',
review: 'review-rank',
newest: 'date-desc-rank',
price_asc: 'price-asc-rank',
price_desc: 'price-desc-rank',
bestseller: 'exact-aware-popularity-rank',
};
export function amazon_product_detail(data, sendResponse) {
return run_pdp_action(data && data.product_url, injected_amazon_product_detail, [], 'amazon_product_detail', sendResponse);
function parse_limit(data, default_val, max_val) {
const n = data && Object.prototype.hasOwnProperty.call(data, 'limit') ? Number(data.limit) : default_val;
if (!Number.isFinite(n)) return default_val;
return Math.max(1, Math.min(max_val, Math.floor(n)));
}
amazon_product_detail.desc =
'Amazon 商品详情标题、价格、品牌、sku{color[],size[]}、要点、配送摘要等)';
amazon_product_detail.params = {
product_url: { type: 'string', desc: '商品详情页完整 URL含 /dp/ASIN', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
};
// ──────────── 核心业务函数(从 handler 回调中提取) ────────────
export function amazon_product_reviews(data, sendResponse) {
const limit = data && data.limit != null ? Number(data.limit) : 50;
return run_pdp_action(data && data.product_url, injected_amazon_product_reviews, [{ limit }], 'amazon_product_reviews', sendResponse);
}
amazon_product_reviews.desc = 'Amazon 商品页买家评论(详情页 [data-hook=review],条数受页面展示限制)';
amazon_product_reviews.params = {
product_url: { type: 'string', desc: '商品详情页完整 URL', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
limit: { type: 'number', desc: '最多条数(默认 50上限 100', default: 50 },
};
export function amazon_product_detail_reviews(data, sendResponse) {
const limit = data && data.limit != null ? Number(data.limit) : 50;
const skip_detail = data && data.skip_detail === true;
const steps = [];
if (!skip_detail) {
steps.push({ name: 'detail', injected_fn: injected_amazon_product_detail, inject_args: [] });
/**
* 搜索列表:验证码检测 -> 首页搜索 -> 排序 -> 分页抓取
*/
async function do_search_list(tab, { keyword, sort_s, category_keyword, sort_by, limit }) {
// DOM 检测验证码页
const captcha_ret = await tab.execute_script(injected_detect_captcha_page, [], 'document_idle');
if (pick_first_script_result(captcha_ret) === true) {
await try_solve_amazon_validate_captcha(tab, 3);
}
steps.push({ name: 'reviews', injected_fn: injected_amazon_product_reviews, inject_args: [{ limit }] });
return run_pdp_action_multi(data && data.product_url, steps, 'amazon_product_detail_reviews', sendResponse);
}
function run_pdp_action(product_url, injected_fn, inject_args, action_name, sendResponse) {
const send_action = (action, payload) => {
if (typeof sendResponse === 'function') {
sendResponse({ action, data: payload });
sendResponse.log && sendResponse.log(payload);
// 首页搜索
const home_ret = await tab.execute_script(injected_amazon_homepage_search, [{ keyword }], 'document_idle');
const home_ok = pick_first_script_result(home_ret);
if (!home_ok || !home_ok.ok) {
const current_url = await get_tab_url(tab.id).catch(() => '');
const detail = home_ok && typeof home_ok === 'object' ? JSON.stringify(home_ok) : String(home_ok);
throw new Error(`首页搜索提交失败: ${detail}; url=${current_url || 'unknown'}`);
}
// 等待跳转到列表页
let url = await wait_until_search_list_url(tab.id, 45000);
await tab.wait_complete();
// 排序
if (sort_s) {
const u = new URL(url);
u.searchParams.set('s', sort_s);
url = u.toString();
await tab.navigate(url);
await tab.wait_complete();
}
// 分页抓取
const unique_map = new Map();
let next_url = url;
for (let page = 1; page <= 10 && unique_map.size < limit; page += 1) {
if (page > 1) {
await tab.navigate(next_url);
await tab.wait_complete();
}
};
return new Promise((resolve, reject) => {
let url = product_url;
Promise.resolve()
.then(() => normalize_product_url(product_url))
.then((normalized_url) => {
url = normalized_url;
const tab_task = create_tab_task(url).set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
return tab_task.open_async();
})
.then((tab) => {
tab.on_update_complete(async () => {
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
await try_solve_amazon_validate_captcha(tab, 3);
const raw_list = await tab.execute_script(injected_fn, inject_args || [], 'document_idle');
const result = Array.isArray(raw_list) ? raw_list[0] : raw_list;
send_action(action_name, ok_response({ tab_id: tab.id, product_url: url, result }));
resolve({ tab_id: tab.id, product_url: url, result });
tab.remove(0);
}, {
once: true,
on_error: (err) => {
send_action(action_name, fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: url,
}));
reject(err);
},
});
})
.catch((err) => {
const is_bad_request = (err && err.message) === '缺少 product_url'
|| (err && err.message) === 'product_url 需为亚马逊域名'
|| (err && err.message) === 'product_url 需包含 /dp/ASIN 或 /gp/product/ASIN';
send_action(action_name, fail_response((err && err.message) || String(err), {
code: is_bad_request ? response_code.bad_request : response_code.runtime_error,
documentURI: is_bad_request ? undefined : url,
}));
reject(err);
});
});
const raw = await tab.execute_script(injected_amazon_search_list, [{ url: next_url, category_keyword, sort_by }], 'document_idle');
const result = pick_first_script_result(raw);
const items = result && Array.isArray(result.items) ? result.items : [];
items.forEach((it) => {
const k = it && (it.asin || it.url) ? String(it.asin || it.url) : null;
if (k && !unique_map.has(k)) unique_map.set(k, it);
});
if (unique_map.size >= limit) break;
next_url = result && result.next_url ? String(result.next_url) : null;
if (!next_url) break;
}
const list_result = { stage: 'list', limit, total: unique_map.size, items: Array.from(unique_map.values()).slice(0, limit) };
return { tab_id: tab.id, url, category_keyword, sort_by: sort_by || 'featured', limit, result: list_result };
}
function run_pdp_action_multi(product_url, steps, action_name, sendResponse) {
const send_action = (action, payload) => {
if (typeof sendResponse === 'function') {
sendResponse({ action, data: payload });
sendResponse.log && sendResponse.log(payload);
}
};
return new Promise((resolve, reject) => {
let url = product_url;
Promise.resolve()
.then(() => normalize_product_url(product_url))
.then((normalized_url) => {
url = normalized_url;
const tab_task = create_tab_task(url).set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
return tab_task.open_async();
})
.then((tab) => {
tab.on_update_complete(async () => {
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
await try_solve_amazon_validate_captcha(tab, 3);
const results = {};
for (const step of steps || []) {
if (!step || !step.name || typeof step.injected_fn !== 'function') continue;
const raw_list = await tab.execute_script(step.injected_fn, step.inject_args || [], 'document_idle');
const result = Array.isArray(raw_list) ? raw_list[0] : raw_list;
results[step.name] = result;
}
send_action(action_name, ok_response({ tab_id: tab.id, product_url: url, result: results }));
resolve({ tab_id: tab.id, product_url: url, result: results });
tab.remove(0);
}, {
once: true,
on_error: (err) => {
send_action(action_name, fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: url,
}));
reject(err);
},
});
})
.catch((err) => {
const is_bad_request = (err && err.message) === '缺少 product_url'
|| (err && err.message) === 'product_url 需为亚马逊域名'
|| (err && err.message) === 'product_url 需包含 /dp/ASIN 或 /gp/product/ASIN';
send_action(action_name, fail_response((err && err.message) || String(err), {
code: is_bad_request ? response_code.bad_request : response_code.runtime_error,
documentURI: is_bad_request ? undefined : url,
}));
reject(err);
});
});
/**
* 切换语言
*/
async function do_set_language(tab, code) {
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
const raw = await tab.execute_script(injected_amazon_switch_language, [{ lang: code }], 'document_idle');
const inj = pick_first_script_result(raw);
if (!inj || !inj.ok) {
throw new Error((inj && inj.error) || 'switch_language_failed');
}
const final_url = await get_tab_url(tab.id);
return { tab_id: tab.id, lang: inj.lang, url: final_url };
}
amazon_product_detail_reviews.desc = 'Amazon 商品详情 + 评论(同一详情页,支持 skip_detail=true';
amazon_product_detail_reviews.params = {
product_url: { type: 'string', desc: '商品详情页完整 URL含 /dp/ASIN', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
limit: { type: 'number', desc: '最多评论条数(默认 50上限 100', default: 50 },
skip_detail: { type: 'boolean', desc: '当日已拉过详情则跳过详情提取', default: false },
};
/**
* PDP 多步骤注入(detail + reviews 等)
*/
async function do_pdp_steps(tab, url, steps) {
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
await try_solve_amazon_validate_captcha(tab, 3);
const results = {};
for (const step of steps) {
if (!step || !step.name || typeof step.injected_fn !== 'function') continue;
const raw = await tab.execute_script(step.injected_fn, step.inject_args || [], 'document_idle');
results[step.name] = pick_first_script_result(raw);
}
return { tab_id: tab.id, product_url: url, result: results };
}
// ──────────── Action 定义 ────────────
export const amazon_actions = [
{
name: 'amazon_search_list',
desc: 'Amazon 搜索列表:先打开中文首页,搜索框输入类目并搜索,再分页抓取',
params: {
category_keyword: { type: 'string', desc: '类目关键词', default: '野餐包' },
sort_by: { type: 'string', desc: '排序方式featured / price_asc / price_desc / review / newest / bestseller', default: 'featured' },
limit: { type: 'number', desc: '抓取数量上限(默认 100最大 200', default: 100 },
keep_tab_open: { type: 'boolean', desc: '调试用:不自动关闭窗口', default: true },
},
handler: async (data, sendResponse) => {
const send_action = create_send_action(sendResponse);
const category_keyword = data && data.category_keyword ? String(data.category_keyword).trim() : '';
const sort_by = data && data.sort_by ? String(data.sort_by).trim() : '';
const keep_tab_open = data && data.keep_tab_open === true;
const limit = parse_limit(data, 100, 200);
const keyword = category_keyword || 'picnic bag';
const sort_s = SORT_MAP[sort_by] || '';
const tab_task = create_tab_task(AMAZON_ZH_HOME_URL)
.set_latest(false)
.set_bounds({ top: 20, left: 20, width: 1440, height: 900 })
.set_target('__amazon_search_list');
let tab = null;
try {
tab = await tab_task.open_async();
const payload = await tab.wait_update_complete_once(() =>
do_search_list(tab, { keyword, sort_s, category_keyword, sort_by, limit })
);
send_action('amazon_search_list', ok_response(payload));
if (!keep_tab_open) tab.remove(0);
return payload;
} catch (err) {
send_action('amazon_search_list', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: AMAZON_ZH_HOME_URL,
}));
if (tab && !keep_tab_open) tab.remove(0);
throw err;
}
},
},
{
name: 'amazon_set_language',
desc: 'Amazon 顶栏语言切换',
params: {
lang: { type: 'string', desc: 'EN / ES / AR / DE / HE / KO / PT / ZH_CN(默认) / ZH_TW', default: 'ZH_CN' },
},
handler: async (data, sendResponse) => {
const send_action = create_send_action(sendResponse);
const mapping = { EN: 'en_US', ES: 'es_US', AR: 'ar_AE', DE: 'de_DE', HE: 'he_IL', KO: 'ko_KR', PT: 'pt_BR', ZH_CN: 'zh_CN', ZH_TW: 'zh_TW' };
const raw_lang = data && data.lang != null ? String(data.lang).trim().toUpperCase() : 'ZH_CN';
const code = Object.prototype.hasOwnProperty.call(mapping, raw_lang) ? raw_lang : 'ZH_CN';
const tab_task = create_tab_task(AMAZON_HOME_FOR_LANG)
.set_latest(false)
.set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
try {
const tab = await tab_task.open_async();
const payload = await tab.wait_update_complete_once(() => do_set_language(tab, code));
send_action('amazon_set_language', ok_response(payload));
tab.remove(0);
return payload;
} catch (err) {
send_action('amazon_set_language', fail_response((err && err.message) || String(err), {
code: response_code.runtime_error,
documentURI: AMAZON_HOME_FOR_LANG,
}));
throw err;
}
},
},
{
name: 'amazon_product_detail',
desc: 'Amazon 商品详情(标题、价格、品牌、要点、配送摘要等)',
params: {
product_url: { type: 'string', desc: '商品详情页完整 URL含 /dp/ASIN', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
},
handler: async (data, sendResponse) => {
const send_action = create_send_action(sendResponse);
const normalized = guard_sync(() => normalize_product_url(data && data.product_url));
if (!normalized.ok) {
send_action('amazon_product_detail', fail_response((normalized.error && normalized.error.message) || String(normalized.error), { code: response_code.bad_request }));
return;
}
const url = normalized.data;
const tab_task = create_tab_task(url).set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
try {
const tab = await tab_task.open_async();
const payload = await tab.wait_update_complete_once(() =>
do_pdp_steps(tab, url, [{ name: 'detail', injected_fn: injected_amazon_product_detail, inject_args: [] }])
);
send_action('amazon_product_detail', ok_response(payload));
tab.remove(0);
return payload;
} catch (err) {
send_action('amazon_product_detail', fail_response((err && err.message) || String(err), { code: response_code.runtime_error, documentURI: url }));
throw err;
}
},
},
{
name: 'amazon_product_reviews',
desc: 'Amazon 商品页买家评论',
params: {
product_url: { type: 'string', desc: '商品详情页完整 URL', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
limit: { type: 'number', desc: '最多条数(默认 50上限 100', default: 50 },
},
handler: async (data, sendResponse) => {
const send_action = create_send_action(sendResponse);
const normalized = guard_sync(() => normalize_product_url(data && data.product_url));
if (!normalized.ok) {
send_action('amazon_product_reviews', fail_response((normalized.error && normalized.error.message) || String(normalized.error), { code: response_code.bad_request }));
return;
}
const url = normalized.data;
const limit = parse_limit(data, 50, 100);
const tab_task = create_tab_task(url).set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
try {
const tab = await tab_task.open_async();
const payload = await tab.wait_update_complete_once(() =>
do_pdp_steps(tab, url, [{ name: 'reviews', injected_fn: injected_amazon_product_reviews, inject_args: [{ limit }] }])
);
send_action('amazon_product_reviews', ok_response(payload));
tab.remove(0);
return payload;
} catch (err) {
send_action('amazon_product_reviews', fail_response((err && err.message) || String(err), { code: response_code.runtime_error, documentURI: url }));
throw err;
}
},
},
{
name: 'amazon_product_detail_reviews',
desc: 'Amazon 商品详情 + 评论(同一详情页,支持 skip_detail=true',
params: {
product_url: { type: 'string', desc: '商品详情页完整 URL含 /dp/ASIN', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
limit: { type: 'number', desc: '最多评论条数(默认 50上限 100', default: 50 },
skip_detail: { type: 'boolean', desc: '当日已拉过详情则跳过详情提取', default: false },
},
handler: async (data, sendResponse) => {
const send_action = create_send_action(sendResponse);
const normalized = guard_sync(() => normalize_product_url(data && data.product_url));
if (!normalized.ok) {
send_action('amazon_product_detail_reviews', fail_response((normalized.error && normalized.error.message) || String(normalized.error), { code: response_code.bad_request }));
return;
}
const url = normalized.data;
const limit = parse_limit(data, 50, 100);
const steps = [
...(data && data.skip_detail === true ? [] : [{ name: 'detail', injected_fn: injected_amazon_product_detail, inject_args: [] }]),
{ name: 'reviews', injected_fn: injected_amazon_product_reviews, inject_args: [{ limit }] },
];
const tab_task = create_tab_task(url).set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
try {
const tab = await tab_task.open_async();
const payload = await tab.wait_update_complete_once(() => do_pdp_steps(tab, url, steps));
send_action('amazon_product_detail_reviews', ok_response(payload));
tab.remove(0);
return payload;
} catch (err) {
send_action('amazon_product_detail_reviews', fail_response((err && err.message) || String(err), { code: response_code.runtime_error, documentURI: url }));
throw err;
}
},
},
];

View File

@@ -1,70 +1,43 @@
// Amazon注入函数 + action 实现amazon.js 仅保留 action 壳)
import { sleep_ms, get_tab_url } from '../libs/index.js';
// Amazon页面注入函数 + 纯工具
//
// 约定:
// - injected_* 在页面上下文执行,只依赖 DOM
// - 每个 action 打开 tab 后,通过 tab.set_on_complete_inject 绑定 onUpdated(status=complete) 注入钩子
// - 闭包外变量不会进入页面,辅助函数只能写在各 injected_* 函数体内
// ---------- 页面注入(仅依赖页面 DOM ----------
function dispatch_human_click(target_el, options) {
const el = target_el;
if (!el) return false;
options = options && typeof options === 'object' ? options : {};
const pointer_id = Number.isFinite(options.pointer_id) ? options.pointer_id : 1;
const pointer_type = options.pointer_type ? String(options.pointer_type) : 'mouse';
try { el.scrollIntoView({ block: 'center', inline: 'center' }); } catch (_) { }
try { el.focus && el.focus(); } catch (_) { }
const rect = el.getBoundingClientRect();
const ox = Number.isFinite(options.offset_x) ? options.offset_x : 0;
const oy = Number.isFinite(options.offset_y) ? options.offset_y : 0;
const x = Math.max(1, Math.floor(rect.left + rect.width / 2 + ox));
const y = Math.max(1, Math.floor(rect.top + rect.height / 2 + oy));
const base = { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y };
try {
if (typeof PointerEvent === 'function') {
el.dispatchEvent(new PointerEvent('pointerover', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerenter', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointermove', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerdown', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true, buttons: 1 }));
el.dispatchEvent(new PointerEvent('pointerup', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true, buttons: 0 }));
}
} catch (_) { }
el.dispatchEvent(new MouseEvent('mousemove', base));
el.dispatchEvent(new MouseEvent('mouseover', base));
el.dispatchEvent(new MouseEvent('mousedown', base));
el.dispatchEvent(new MouseEvent('mouseup', base));
el.dispatchEvent(new MouseEvent('click', base));
return true;
}
// ──────────── 验证码相关 ────────────
export function injected_amazon_validate_captcha_continue() {
const href = location.href || '';
const is_captcha = href.includes('/errors/validateCaptcha');
if (!is_captcha) return { ok: true, is_captcha: false, clicked: false, href };
const injected_utils = () => window.__mv2_simple_injected || null;
const dispatch_human_click = (target_el) => {
const u = injected_utils();
if (u && typeof u.dispatch_human_click === 'function') return u.dispatch_human_click(target_el);
return false;
};
// 基于 DOM 特征判断验证码页
const form = document.querySelector('form[action*="/errors/validateCaptcha"]');
if (!form) return { ok: true, is_captcha: false, clicked: false, href: location.href };
const btn =
document.querySelector('form[action="/errors/validateCaptcha"] button[type="submit"].a-button-text') ||
document.querySelector('form[action*="validateCaptcha"] input[type="submit"]') ||
document.querySelector('form[action*="validateCaptcha"] button[type="submit"]') ||
form.querySelector('button[type="submit"].a-button-text') ||
form.querySelector('input[type="submit"]') ||
form.querySelector('button[type="submit"]') ||
document.querySelector('input[type="submit"][value*="Continue"]') ||
document.querySelector('button[type="submit"]');
const clicked = btn ? dispatch_human_click(btn) : false;
if (!clicked) {
const form = document.querySelector('form[action*="validateCaptcha"]');
if (form) {
try {
form.submit();
return { ok: true, is_captcha: true, clicked: true, method: 'submit', href };
} catch (_) { }
try {
form.submit();
return { ok: true, is_captcha: true, clicked: true, method: 'submit', href: location.href };
} catch (_) {
return { ok: false, is_captcha: true, clicked: false, method: 'submit', href: location.href };
}
}
return { ok: true, is_captcha: true, clicked, method: clicked ? 'dispatch' : 'none', href };
return { ok: true, is_captcha: true, clicked, method: clicked ? 'dispatch' : 'none', href: location.href };
}
export function is_amazon_validate_captcha_url(tab_url) {
@@ -72,18 +45,25 @@ export function is_amazon_validate_captcha_url(tab_url) {
return tab_url.includes('amazon.') && tab_url.includes('/errors/validateCaptcha');
}
export function sleep_ms(ms) {
const t = Number(ms);
return new Promise((resolve) => setTimeout(resolve, Number.isFinite(t) ? Math.max(0, t) : 0));
/**
* 基于 DOM 特征检测验证码页(注入到页面执行)
*/
export function injected_detect_captcha_page() {
const form = document.querySelector('form[action*="/errors/validateCaptcha"]');
const btn = document.querySelector(
'form[action*="/errors/validateCaptcha"] button[type="submit"], form[action*="/errors/validateCaptcha"] input[type="submit"]'
);
const has_continue_h4 = Array.from(document.querySelectorAll('h4')).some((el) => {
const txt = (el.textContent || '').trim().toLowerCase();
return txt.includes('continue shopping');
});
return !!(form && (btn || has_continue_h4));
}
export async function try_solve_amazon_validate_captcha(tab, max_round) {
const rounds = Number.isFinite(max_round) ? Math.max(1, Math.min(5, Math.floor(max_round))) : 2;
for (let i = 0; i < rounds; i += 1) {
const tab_state = await new Promise((resolve) => {
chrome.tabs.get(tab.id, (t) => resolve(t || null));
});
const url = tab_state && tab_state.url ? String(tab_state.url) : '';
const url = await get_tab_url(tab.id).catch(() => '');
if (!is_amazon_validate_captcha_url(url)) return true;
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
await sleep_ms(800 + Math.floor(Math.random() * 600));
@@ -93,25 +73,32 @@ export async function try_solve_amazon_validate_captcha(tab, max_round) {
return false;
}
// ──────────── 结果工具 ────────────
export function pick_first_script_result(raw_list) {
if (!Array.isArray(raw_list) || raw_list.length === 0) return null;
const first = raw_list[0];
if (first && typeof first === 'object' && Object.prototype.hasOwnProperty.call(first, 'result')) {
return first.result;
}
return first;
}
// ──────────── 首页搜索(注入) ────────────
export function injected_amazon_homepage_search(params) {
const injected_utils = () => window.__mv2_simple_injected || null;
const dispatch_human_click = (target_el) => {
const u = injected_utils();
if (u && typeof u.dispatch_human_click === 'function') return u.dispatch_human_click(target_el);
return false;
};
const keyword = params && params.keyword ? String(params.keyword).trim() : '';
if (!keyword) return { ok: false, error: 'empty_keyword' };
function wait_query(selectors, timeout_ms) {
const list = Array.isArray(selectors) ? selectors : [];
const deadline = Date.now() + (Number.isFinite(timeout_ms) ? timeout_ms : 5000);
while (Date.now() < deadline) {
for (const sel of list) {
const el = document.querySelector(sel);
if (!el) continue;
const r = el.getBoundingClientRect();
if (r.width > 0 && r.height > 0) return el;
}
const t0 = performance.now();
while (performance.now() - t0 < 40) { }
}
return null;
}
const u = injected_utils();
const wait_query = u && typeof u.wait_query === 'function' ? u.wait_query : () => null;
const set_input_value = u && typeof u.set_input_value === 'function' ? u.set_input_value : () => false;
const input = wait_query([
'#twotabsearchtextbox',
@@ -120,10 +107,8 @@ export function injected_amazon_homepage_search(params) {
'input[type="search"][name="field-keywords"]',
], 7000);
if (!input) return { ok: false, error: 'no_search_input' };
input.focus();
input.value = keyword;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
set_input_value(input, keyword);
const btn = wait_query([
'#nav-search-submit-button',
'#nav-search-bar-form input[type="submit"]',
@@ -133,44 +118,48 @@ export function injected_amazon_homepage_search(params) {
'input.nav-input[type="submit"]',
], 2000);
if (btn) {
return { ok: dispatch_human_click(btn) };
const clicked = dispatch_human_click(btn);
if (clicked) return { ok: true, method: 'button_click' };
}
const form = input.form || input.closest('form');
if (form && typeof form.requestSubmit === 'function') {
form.requestSubmit();
return { ok: true, method: 'request_submit' };
try { form.requestSubmit(); return { ok: true, method: 'request_submit' }; } catch (_) {}
}
if (form && typeof form.submit === 'function') {
form.submit();
return { ok: true, method: 'form_submit' };
try { form.submit(); return { ok: true, method: 'form_submit' }; } catch (_) {}
}
try {
input.focus();
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
input.dispatchEvent(new KeyboardEvent('keypress', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
input.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
if (form) form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
return { ok: true, method: 'keyboard_enter' };
} catch (_) {
// ignore and return explicit error
}
return { ok: false, error: 'no_submit', keyword };
} catch (_) {}
return { ok: false, error: 'submit_all_fallback_failed', keyword };
}
// ──────────── 切换语言(注入) ────────────
export function injected_amazon_switch_language(params) {
const injected_utils = () => window.__mv2_simple_injected || null;
const dispatch_human_click = (target_el) => {
const u = injected_utils();
if (u && typeof u.dispatch_human_click === 'function') return u.dispatch_human_click(target_el);
return false;
};
const mapping = {
EN: 'en_US',
ES: 'es_US',
AR: 'ar_AE',
DE: 'de_DE',
HE: 'he_IL',
KO: 'ko_KR',
PT: 'pt_BR',
ZH_CN: 'zh_CN',
ZH_TW: 'zh_TW',
EN: 'en_US', ES: 'es_US', AR: 'ar_AE', DE: 'de_DE',
HE: 'he_IL', KO: 'ko_KR', PT: 'pt_BR', ZH_CN: 'zh_CN', ZH_TW: 'zh_TW',
};
const raw = params && params.lang != null ? String(params.lang).trim().toUpperCase() : 'ZH_CN';
const code = Object.prototype.hasOwnProperty.call(mapping, raw) ? raw : 'ZH_CN';
const switch_lang = mapping[code];
const href_sel = `a[href="#switch-lang=${switch_lang}"]`;
const u = injected_utils();
const deadline = Date.now() + 6000;
let link = null;
while (Date.now() < deadline) {
@@ -179,8 +168,7 @@ export function injected_amazon_switch_language(params) {
const r = link.getBoundingClientRect();
if (r.width > 0 && r.height > 0) break;
}
const t0 = performance.now();
while (performance.now() - t0 < 40) { }
if (u && typeof u.busy_wait_ms === 'function') u.busy_wait_ms(40);
}
if (!link) return { ok: false, error: 'lang_option_timeout', lang: code };
dispatch_human_click(link);
@@ -193,97 +181,47 @@ export function injected_amazon_switch_language(params) {
document.querySelector('input[type="submit"][aria-labelledby*="icp-save-button"]') ||
document.querySelector('span.icp-save-button input[type="submit"]');
if (save) break;
const t1 = performance.now();
while (performance.now() - t1 < 40) { }
}
if (save) {
dispatch_human_click(save);
if (u && typeof u.busy_wait_ms === 'function') u.busy_wait_ms(40);
}
if (save) dispatch_human_click(save);
return { ok: true, lang: code };
}
// ──────────── 搜索列表(注入) ────────────
export function injected_amazon_search_list(params) {
const injected_utils = () => window.__mv2_simple_injected || null;
const dispatch_human_click = (target_el) => {
const u = injected_utils();
if (u && typeof u.dispatch_human_click === 'function') return u.dispatch_human_click(target_el);
return false;
};
params = params && typeof params === 'object' ? params : {};
const debug = params.debug === true;
const u = injected_utils();
// validateCaptcha:在 onUpdated(complete) 钩子里也能自动处理
// validateCaptcha 页面:直接点击继续
if ((location.href || '').includes('/errors/validateCaptcha')) {
function dispatch_human_click_local(el) {
if (!el) return false;
try { el.scrollIntoView({ block: 'center', inline: 'center' }); } catch (_) { }
try { el.focus && el.focus(); } catch (_) { }
const rect = el.getBoundingClientRect();
const x = Math.max(1, Math.floor(rect.left + rect.width / 2));
const y = Math.max(1, Math.floor(rect.top + rect.height / 2));
const base = { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y };
try {
if (typeof PointerEvent === 'function') {
el.dispatchEvent(new PointerEvent('pointerover', { ...base, pointerId: 1, pointerType: 'mouse', isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerenter', { ...base, pointerId: 1, pointerType: 'mouse', isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointermove', { ...base, pointerId: 1, pointerType: 'mouse', isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerdown', { ...base, pointerId: 1, pointerType: 'mouse', isPrimary: true, buttons: 1 }));
el.dispatchEvent(new PointerEvent('pointerup', { ...base, pointerId: 1, pointerType: 'mouse', isPrimary: true, buttons: 0 }));
}
} catch (_) { }
el.dispatchEvent(new MouseEvent('mousemove', base));
el.dispatchEvent(new MouseEvent('mouseover', base));
el.dispatchEvent(new MouseEvent('mousedown', base));
el.dispatchEvent(new MouseEvent('mouseup', base));
el.dispatchEvent(new MouseEvent('click', base));
return true;
}
const btn =
document.querySelector('form[action="/errors/validateCaptcha"] button[type="submit"].a-button-text') ||
document.querySelector('form[action*="validateCaptcha"] input[type="submit"]') ||
document.querySelector('form[action*="validateCaptcha"] button[type="submit"]') ||
document.querySelector('input[type="submit"][value*="Continue"]') ||
document.querySelector('button[type="submit"]');
const clicked = btn ? dispatch_human_click_local(btn) : false;
if (debug) {
// eslint-disable-next-line no-console
console.log('[amazon][on_complete] validateCaptcha', { clicked, href: location.href });
}
const clicked = btn ? dispatch_human_click(btn) : false;
if (debug) console.log('[amazon][on_complete] validateCaptcha', { clicked, href: location.href });
return { stage: 'captcha', href: location.href, clicked };
}
const start_url = params && params.url ? String(params.url) : location.href;
const category_keyword = params && params.category_keyword ? String(params.category_keyword).trim() : '';
const sort_by = params && params.sort_by ? String(params.sort_by).trim() : '';
const start_url = params.url ? String(params.url) : location.href;
const category_keyword = params.category_keyword ? String(params.category_keyword).trim() : '';
const sort_by = params.sort_by ? String(params.sort_by).trim() : '';
function pick_number(text) {
if (!text) return null;
const s = String(text).replace(/[(),]/g, ' ').replace(/\s+/g, ' ').trim();
const m = s.match(/(\d+(?:\.\d+)?)/);
return m ? Number(m[1]) : null;
}
function pick_int(text) {
if (!text) return null;
const raw = String(text).replace(/\s+/g, ' ').trim();
const u = raw.toUpperCase().replace(/,/g, '');
const km = u.match(/([\d.]+)\s*K\b/);
if (km) return Math.round(parseFloat(km[1]) * 1000);
const mm = u.match(/([\d.]+)\s*M\b/);
if (mm) return Math.round(parseFloat(mm[1]) * 1000000);
const digits = raw.replace(/[^\d]/g, '');
return digits ? Number(digits) : null;
}
function abs_url(href) {
try {
return new URL(href, location.origin).toString();
} catch (_) {
return href;
}
}
function parse_asin_from_url(url) {
if (!url || typeof url !== 'string') return null;
const m = url.match(/\/dp\/([A-Z0-9]{10})/i) || url.match(/\/gp\/product\/([A-Z0-9]{10})/i);
return m ? m[1].toUpperCase() : null;
}
const abs_url = u && typeof u.abs_url === 'function' ? u.abs_url : (x) => x;
const parse_asin_from_url = u && typeof u.parse_asin_from_url === 'function' ? u.parse_asin_from_url : () => null;
const pick_number = u && typeof u.pick_number === 'function' ? u.pick_number : () => null;
const pick_int = u && typeof u.pick_int === 'function' ? u.pick_int : () => null;
function extract_results() {
const items = [];
@@ -327,13 +265,8 @@ export function injected_amazon_search_list(params) {
items.push({
index: idx + 1,
asin: asin || parse_asin_from_url(item_url),
title,
url: item_url,
price,
rating,
rating_text,
review_count,
review_count_text,
title, url: item_url, price,
rating, rating_text, review_count, review_count_text,
});
});
return items;
@@ -342,40 +275,32 @@ export function injected_amazon_search_list(params) {
function pick_next_url() {
const a = document.querySelector('a.s-pagination-next');
if (!a) return null;
const aria_disabled = (a.getAttribute('aria-disabled') || '').trim().toLowerCase();
if (aria_disabled === 'true') return null;
if ((a.getAttribute('aria-disabled') || '').trim().toLowerCase() === 'true') return null;
if (a.classList && a.classList.contains('s-pagination-disabled')) return null;
const href = a.getAttribute('href');
if (!href) return null;
return abs_url(href);
return href ? abs_url(href) : null;
}
const items = extract_results();
const out = { start_url, href: location.href, category_keyword, sort_by, total: items.length, items, next_url: pick_next_url() };
if (debug) {
// eslint-disable-next-line no-console
console.log('[amazon][on_complete] search_list', {
href: out.href,
total: out.total,
has_next: !!out.next_url,
});
try {
window.__amazon_debug_last_search_list = out;
} catch (_) { }
console.log('[amazon][on_complete] search_list', { href: out.href, total: out.total, has_next: !!out.next_url });
try { window.__amazon_debug_last_search_list = out; } catch (_) {}
}
return out;
}
// ──────────── 商品详情(注入) ────────────
export function injected_amazon_product_detail() {
const norm = (s) => (s || '').replace(/\s+/g, ' ').trim();
const u = window.__mv2_simple_injected || null;
const norm = u && typeof u.norm_space === 'function' ? u.norm_space : (s) => (s || '').replace(/\s+/g, ' ').trim();
const asin_match = location.pathname.match(/\/(?:dp|gp\/product)\/([A-Z0-9]{10})/i);
const asin = asin_match ? asin_match[1].toUpperCase() : null;
const product_info = {};
function set_info(k, v, max_len) {
k = norm(k);
v = norm(v);
max_len = max_len || 600;
k = norm(k); v = norm(v); max_len = max_len || 600;
if (!k || !v || k.length > 100) return;
if (v.length > max_len) v = v.slice(0, max_len);
if (!product_info[k] || v.length > product_info[k].length) product_info[k] = v;
@@ -434,25 +359,16 @@ export function injected_amazon_product_detail() {
if (del) delivery_hint = norm(del.innerText).slice(0, 500);
return {
stage: 'detail',
asin,
title,
price,
brand_line,
brand_store_url,
rating_stars,
review_count_text,
ac_badge,
social_proof,
bestseller_hint,
product_info,
detail_extra_lines,
bullets,
delivery_hint,
stage: 'detail', asin, title, price,
brand_line, brand_store_url, rating_stars, review_count_text,
ac_badge, social_proof, bestseller_hint,
product_info, detail_extra_lines, bullets, delivery_hint,
url: location.href,
};
}
// ──────────── 商品评论(注入) ────────────
export function injected_amazon_product_reviews(params) {
const raw = params && params.limit != null ? Number(params.limit) : 50;
const limit = Number.isFinite(raw) ? Math.max(1, Math.min(100, Math.floor(raw))) : 50;
@@ -477,6 +393,8 @@ export function injected_amazon_product_reviews(params) {
return { stage: 'reviews', limit, total: items.length, items, url: location.href };
}
// ──────────── URL 工具 ────────────
export function normalize_product_url(u) {
let s = u ? String(u).trim() : '';
if (!s) throw new Error('缺少 product_url');
@@ -497,18 +415,15 @@ export function is_amazon_search_list_url(tab_url) {
return tab_url.includes('k=') || tab_url.includes('keywords=') || tab_url.includes('field-keywords');
}
export function wait_until_search_list_url(tab_id, timeout_ms) {
const deadline = Date.now() + (timeout_ms || 45000);
return new Promise((resolve, reject) => {
const tick = () => {
chrome.tabs.get(tab_id, (tab) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
const u = tab && tab.url ? tab.url : '';
if (is_amazon_search_list_url(u)) return resolve(u);
if (Date.now() >= deadline) return reject(new Error('等待首页搜索跳转到列表页超时'));
setTimeout(tick, 400);
});
};
tick();
});
/**
* 轮询等待 tab URL 变为搜索列表页async 循环,替代旧版回调递归)
*/
export async function wait_until_search_list_url(tab_id, timeout_ms = 45000) {
const deadline = Date.now() + timeout_ms;
while (Date.now() < deadline) {
const url = await get_tab_url(tab_id);
if (is_amazon_search_list_url(url)) return url;
await sleep_ms(400);
}
throw new Error('等待首页搜索跳转到列表页超时');
}

View File

@@ -0,0 +1,38 @@
/**
* 统一的动作导出
* 使用现代 ES6 模块化方式,提供统一的动作接口
*/
// Amazon 相关动作
import { amazon_actions } from './amazon.js';
export { amazon_actions };
// 获取所有动作的元信息
export function getAllActionsMeta() {
const meta = {};
if (Array.isArray(amazon_actions)) {
amazon_actions.forEach((item) => {
if (item && item.name) {
meta[item.name] = {
name: item.name,
desc: item.desc || '',
params: item.params || {},
};
}
});
}
return meta;
}
// 根据名称获取动作
export function getActionByName(name) {
if (!Array.isArray(amazon_actions)) return null;
return amazon_actions.find(item => item && item.name === name);
}
export default {
amazon: amazon_actions,
};;

View File

@@ -1,35 +1,43 @@
import { amazon_actions, getAllActionsMeta, getActionByName } from '../actions/index.js';
import {
amazon_search_list,
amazon_set_language,
amazon_product_detail,
amazon_product_reviews,
amazon_product_detail_reviews,
} from '../actions/amazon.js';
// ──────────── Action 注册 ────────────
// action 注册表:供 UI 下拉选择 + server bridge 调用
const actions = {
amazon_search_list,
amazon_set_language,
amazon_product_detail,
amazon_product_reviews,
amazon_product_detail_reviews,
};
function list_actions_meta() {
const meta = {};
Object.keys(actions).forEach((name) => {
const fn = actions[name];
meta[name] = {
name,
desc: fn && fn.desc ? fn.desc : '',
params: fn && fn.params ? fn.params : {},
};
});
return meta;
let action_list = [];
try {
if (Array.isArray(amazon_actions)) {
action_list = amazon_actions.filter(item => item && typeof item === 'object' && item.name);
console.log(`Loaded ${action_list.length} actions:`, action_list.map(item => item.name));
} else {
console.warn('amazon_actions is not an array:', amazon_actions);
}
} catch (error) {
console.error('Failed to load amazon_actions:', error);
}
function create_action_send_response(sender) {
// ──────────── UI 事件推送 ────────────
const ui_page_url = chrome.runtime.getURL('ui/index.html');
const is_port_closed_error = (message) => {
const text = message ? String(message) : '';
return text.includes('The message port closed before a response was received');
};
const emit_ui_event = (event_name, payload) => {
try {
chrome.runtime.sendMessage({ channel: 'ui_event', event_name, payload, ts: Date.now() }, (response) => {
if (chrome.runtime.lastError) {
const err_msg = chrome.runtime.lastError.message;
if (is_port_closed_error(err_msg)) return;
console.warn('Failed to send UI event:', err_msg);
}
});
} catch (error) {
console.error('Error in emit_ui_event:', error);
}
};
const create_action_send_response = (sender) => {
const fn = (payload) => {
emit_ui_event('push', { type: 'reply', ...payload, sender });
};
@@ -37,89 +45,83 @@ function create_action_send_response(sender) {
emit_ui_event('push', { type: 'log', action: 'log', data: payload, sender });
};
return fn;
};
// ──────────── 内置 action 路由 ────────────
const builtin_handlers = {
meta_actions(message, sender, sendResponse) {
console.log('Returning actions meta');
sendResponse({ ok: true, data: getAllActionsMeta() });
},
reload_background(message, sender, sendResponse) {
console.log('Reloading background page');
sendResponse({ ok: true });
setTimeout(() => location.reload(), 50);
},
};
// ──────────── Action 执行器 ────────────
async function execute_action(action_handler, message, sender, sendResponse) {
const request_id = `${Date.now()}_${Math.random().toString().slice(2)}`;
console.log('Executing action:', { action: message.action, request_id, data: message.data });
emit_ui_event('request', { type: 'request', request_id, action: message.action, data: message.data || {}, sender });
const action_send_response = create_action_send_response(sender);
try {
const res = await action_handler(message.data || {}, action_send_response);
console.log(`Action ${message.action} completed successfully:`, { request_id, result: res });
emit_ui_event('response', { type: 'response', request_id, ok: true, data: res, sender });
sendResponse({ ok: true, data: res, request_id });
} catch (err) {
const error = (err && err.message) || String(err);
const stack = (err && err.stack) || '';
console.error(`Action ${message.action} failed:`, { error, stack, data: message.data });
emit_ui_event('response', { type: 'response', request_id, ok: false, error, stack, sender });
sendResponse({ ok: false, error, stack, request_id });
}
}
const ui_page_url = chrome.runtime.getURL('ui/index.html');
function emit_ui_event(event_name, payload) {
chrome.runtime.sendMessage({
channel: 'ui_event',
event_name,
payload,
ts: Date.now(),
});
}
// ──────────── 消息分发 ────────────
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.create({ url: ui_page_url, active: true });
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!message) {
return;
}
// 忽略空消息、UI 自身事件、page world 桥接
if (!message || message.channel === 'ui_event' || message.channel === 'page_exec_bridge') return;
// UI 自己发出来的事件,background 不处理
if (message.channel === 'ui_event') {
return;
}
// content -> background 的推送消息(通用)
// content -> background 推送
if (message.type === 'push') {
emit_ui_event('push', {
type: 'push',
action: message.action,
data: message.data,
sender,
});
console.log('Processing push message:', message.action);
emit_ui_event('push', { type: 'push', action: message.action, data: message.data, sender });
return;
}
// UI -> background 的 action 调用
// 缺少 action
if (!message.action) {
console.error('Missing action in message');
sendResponse && sendResponse({ ok: false, error: '缺少 action' });
return;
}
// UI 获取 action 元信息(用于下拉/默认参数
if (message.action === 'meta_actions') {
sendResponse({ ok: true, data: list_actions_meta() });
// 内置 action(同步处理,不需要 return true
if (builtin_handlers[message.action]) {
builtin_handlers[message.action](message, sender, sendResponse);
return;
}
// UI 刷新后台(重启 background page
if (message.action === 'reload_background') {
sendResponse({ ok: true });
setTimeout(() => {
location.reload();
}, 50);
return;
}
const fn = actions[message.action];
if (!fn) {
// 业务 action
const action_item = getActionByName(message.action);
if (!action_item || typeof action_item.handler !== 'function') {
console.error('Unknown action:', message.action);
sendResponse({ ok: false, error: '未知 action: ' + message.action });
return;
}
const request_id = `${Date.now()}_${Math.random().toString().slice(2)}`;
emit_ui_event('request', { type: 'request', request_id, action: message.action, data: message.data || {}, sender });
const action_send_response = create_action_send_response(sender);
(async () => {
try {
const res = await fn(message.data || {}, action_send_response);
emit_ui_event('response', { type: 'response', request_id, ok: true, data: res, sender });
sendResponse({ ok: true, data: res, request_id });
} catch (err) {
const error = (err && err.message) || String(err);
emit_ui_event('response', { type: 'response', request_id, ok: false, error, sender });
sendResponse({ ok: false, error, request_id });
}
})();
execute_action(action_item.handler, message, sender, sendResponse);
return true;
});

View File

@@ -2,31 +2,37 @@
* 服务端 Puppeteer 通过此页与 background 通讯(等同 UI 发 chrome.runtime.sendMessage
* 页面内若需 Web Worker 做重计算,可在此 postMessage当前直连 background 即可满足指令/结果
*/
(function () {
function server_bridge_invoke(action, data) {
return new Promise(function (resolve, reject) {
(() => {
const server_bridge_invoke = (action, data) => {
return new Promise((resolve, reject) => {
if (!action) {
reject(new Error('缺少 action'));
return;
}
chrome.runtime.sendMessage({ action: action, data: data || {} }, function (res) {
var err = chrome.runtime.lastError;
if (err) {
reject(new Error(err.message));
return;
chrome.runtime.sendMessage(
{ action, data: data || {} },
(res) => {
const err = chrome.runtime.lastError;
if (err) {
reject(new Error(err.message));
return;
}
if (!res) {
reject(new Error('background 无响应'));
return;
}
if (res.ok) {
resolve(res.data);
} else {
reject(new Error(res.error || 'action 失败'));
}
}
if (!res) {
reject(new Error('background 无响应'));
return;
}
if (res.ok) {
resolve(res.data);
} else {
reject(new Error(res.error || 'action 失败'));
}
});
);
});
}
};
window.server_bridge_invoke = server_bridge_invoke;
})();

View File

@@ -2,6 +2,29 @@
// 目标:页面里触发 XHR/fetch 时派发 __REQUEST_DONE
(() => {
function inject_page_file_once(file_path, marker) {
const root = document.documentElement || document.head;
if (!root) return false;
const mark_key = marker || file_path;
const attr = `data-mv2-injected-${mark_key.replace(/[^a-z0-9_-]/gi, '_')}`;
if (root.hasAttribute(attr)) return true;
const src = chrome.runtime.getURL(file_path);
const el = document.createElement('script');
el.type = 'text/javascript';
el.src = src;
el.onload = () => {
el.parentNode && el.parentNode.removeChild(el);
};
el.onerror = () => {
el.parentNode && el.parentNode.removeChild(el);
root.removeAttribute(attr);
};
root.setAttribute(attr, '1');
(document.head || document.documentElement).appendChild(el);
return true;
}
function inject_inline(fn) {
const el = document.createElement('script');
el.type = 'text/javascript';
@@ -161,5 +184,8 @@
F.__RequestWatcher = true;
}
// 页面上下文通用方法window.__mv2_simple_injected
inject_page_file_once('injected/injected.js', 'core_utils');
inject_inline(request_watcher);
})();

View File

@@ -0,0 +1,53 @@
/**
* 使用新模块化方式的示例
* 展示如何使用统一的导出接口
*/
// 方式1: 命名导入(推荐)
import { ok_response, fail_response, create_tab_task, amazon_actions, getAllActionsMeta, getActionByName } from '../libs/index.js';
// 方式2: 默认导入使用对象
import Libs from '../libs/index.js';
import Actions from '../actions/index.js';
// 示例函数
export async function exampleAction() {
// 使用命名导入
const response = ok_response({ success: true });
// 使用默认导入
const task = Libs.tabs.createTask('https://example.com');
// 使用 Actions
const allMeta = getAllActionsMeta();
const specificAction = getActionByName('amazon_search_list');
return {
response,
task,
allMeta,
specificAction
};
}
// 更简洁的写法
export const ModernUsage = {
// 响应处理
response: {
success: (data) => ok_response(data),
error: (msg) => fail_response(msg)
},
// Tab 操作
tabs: {
create: (url) => create_tab_task(url),
// ... 其他操作
},
// 动作管理
actions: {
getAll: getAllActionsMeta,
get: getActionByName,
list: amazon_actions
}
};

View File

@@ -0,0 +1,148 @@
(() => {
if (window.__mv2_simple_injected) return;
const norm_space = (s) => (s || '').toString().replace(/\s+/g, ' ').trim();
const busy_wait_ms = (ms) => {
const t = Number(ms);
const dur = Number.isFinite(t) ? Math.max(0, t) : 0;
const t0 = performance.now();
while (performance.now() - t0 < dur) { }
};
const is_visible = (el) => {
if (!el) return false;
const r = el.getBoundingClientRect();
if (!(r.width > 0 && r.height > 0)) return false;
// 尽量避免点击到不可见层display/visibility 由浏览器计算
const cs = window.getComputedStyle(el);
if (!cs) return true;
if (cs.display === 'none') return false;
if (cs.visibility === 'hidden') return false;
if (cs.opacity === '0') return false;
return true;
};
const wait_query = (selectors, timeout_ms) => {
const list = Array.isArray(selectors) ? selectors : [];
const deadline = Date.now() + (Number.isFinite(timeout_ms) ? timeout_ms : 5000);
while (Date.now() < deadline) {
for (let i = 0; i < list.length; i += 1) {
const sel = list[i];
const el = document.querySelector(sel);
if (is_visible(el)) return el;
}
busy_wait_ms(40);
}
return null;
};
const dispatch_human_click = (target_el, options) => {
const el = target_el;
if (!el) return false;
const opt = options && typeof options === 'object' ? options : {};
const pointer_id = Number.isFinite(opt.pointer_id) ? opt.pointer_id : 1;
const pointer_type = opt.pointer_type ? String(opt.pointer_type) : 'mouse';
try { el.scrollIntoView({ block: 'center', inline: 'center' }); } catch (_) { }
try { el.focus && el.focus(); } catch (_) { }
const rect = el.getBoundingClientRect();
const ox = Number.isFinite(opt.offset_x) ? opt.offset_x : 0;
const oy = Number.isFinite(opt.offset_y) ? opt.offset_y : 0;
const x = Math.max(1, Math.floor(rect.left + rect.width / 2 + ox));
const y = Math.max(1, Math.floor(rect.top + rect.height / 2 + oy));
const base = { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y };
try {
if (typeof PointerEvent === 'function') {
el.dispatchEvent(new PointerEvent('pointerover', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerenter', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointermove', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true }));
el.dispatchEvent(new PointerEvent('pointerdown', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true, buttons: 1 }));
el.dispatchEvent(new PointerEvent('pointerup', { ...base, pointerId: pointer_id, pointerType: pointer_type, isPrimary: true, buttons: 0 }));
}
} catch (_) { }
el.dispatchEvent(new MouseEvent('mousemove', base));
el.dispatchEvent(new MouseEvent('mouseover', base));
el.dispatchEvent(new MouseEvent('mousedown', base));
el.dispatchEvent(new MouseEvent('mouseup', base));
el.dispatchEvent(new MouseEvent('click', base));
return true;
};
const text = (el) => el && el.textContent != null ? norm_space(el.textContent) : null;
const inner_text = (el) => el && el.innerText != null ? norm_space(el.innerText) : null;
const attr = (el, name) => {
if (!el || !name) return null;
const v = el.getAttribute ? el.getAttribute(name) : null;
return v != null ? norm_space(v) : null;
};
const abs_url = (href, base) => {
try {
return new URL(href, base || location.origin).toString();
} catch (_) {
return href;
}
};
const parse_asin_from_url = (url) => {
if (!url || typeof url !== 'string') return null;
const m = url.match(/\/dp\/([A-Z0-9]{10})/i) || url.match(/\/gp\/product\/([A-Z0-9]{10})/i);
return m ? m[1].toUpperCase() : null;
};
const pick_number = (text0) => {
if (!text0) return null;
const s = String(text0).replace(/[(),]/g, ' ').replace(/\s+/g, ' ').trim();
const m = s.match(/(\d+(?:\.\d+)?)/);
return m ? Number(m[1]) : null;
};
const pick_int = (text0) => {
if (!text0) return null;
const raw = String(text0).replace(/\s+/g, ' ').trim();
const up = raw.toUpperCase().replace(/,/g, '');
const km = up.match(/([\d.]+)\s*K\b/);
if (km) return Math.round(parseFloat(km[1]) * 1000);
const mm = up.match(/([\d.]+)\s*M\b/);
if (mm) return Math.round(parseFloat(mm[1]) * 1000000);
const digits = raw.replace(/[^\d]/g, '');
return digits ? Number(digits) : null;
};
const set_input_value = (input, value, options) => {
if (!input) return false;
const opt = options && typeof options === 'object' ? options : {};
try { input.focus && input.focus(); } catch (_) { }
try { input.value = value == null ? '' : String(value); } catch (_) { return false; }
if (opt.dispatch_input !== false) {
try { input.dispatchEvent(new Event('input', { bubbles: true })); } catch (_) { }
}
if (opt.dispatch_change !== false) {
try { input.dispatchEvent(new Event('change', { bubbles: true })); } catch (_) { }
}
return true;
};
window.__mv2_simple_injected = {
norm_space: norm_space,
busy_wait_ms: busy_wait_ms,
wait_query: wait_query,
is_visible: is_visible,
dispatch_human_click: dispatch_human_click,
text: text,
inner_text: inner_text,
attr: attr,
abs_url: abs_url,
parse_asin_from_url: parse_asin_from_url,
pick_number: pick_number,
pick_int: pick_int,
set_input_value: set_input_value,
};
})();

View File

@@ -0,0 +1,13 @@
// 统一绑定 action 元数据:集中配置,同时兼容历史 fn.desc/fn.params 读取方式。
export function bind_action_meta(action_map, meta_map) {
const actions = action_map && typeof action_map === 'object' ? action_map : {};
const metas = meta_map && typeof meta_map === 'object' ? meta_map : {};
Object.keys(metas).forEach((action_name) => {
const action_fn = actions[action_name];
const meta = metas[action_name] || {};
if (typeof action_fn !== 'function') return;
action_fn.desc = meta.desc || '';
action_fn.params = meta.params || {};
});
return metas;
}

View File

@@ -2,6 +2,7 @@ const RESPONSE_CODE_OK = 0;
const RESPONSE_CODE_BAD_REQUEST = 10;
const RESPONSE_CODE_RUNTIME_ERROR = 30;
// 成功响应工厂:统一返回结构与成功码。
export function ok_response(data) {
return {
code: RESPONSE_CODE_OK,
@@ -11,6 +12,7 @@ export function ok_response(data) {
};
}
// 失败响应工厂:统一错误码、错误消息和可选上下文。
export function fail_response(message, options) {
const opts = options && typeof options === 'object' ? options : {};
const code = Number.isFinite(opts.code) ? Number(opts.code) : RESPONSE_CODE_RUNTIME_ERROR;
@@ -25,8 +27,18 @@ export function fail_response(message, options) {
};
}
// 响应码常量:供业务层统一引用,避免魔法数字。
export const response_code = {
ok: RESPONSE_CODE_OK,
bad_request: RESPONSE_CODE_BAD_REQUEST,
runtime_error: RESPONSE_CODE_RUNTIME_ERROR,
};
// 同步执行保护:把同步异常转为统一结果对象,避免业务层到处写 try/catch。
export function guard_sync(task) {
try {
return { ok: true, data: task() };
} catch (error) {
return { ok: false, error };
}
}

View File

@@ -0,0 +1,61 @@
/**
* 统一的库函数导出
* 使用现代 ES6 模块化方式,提供统一的功能接口
*/
// 响应处理相关
import { ok_response, fail_response, response_code, guard_sync } from './action_response.js';
export { ok_response, fail_response, response_code, guard_sync };
// Tab 操作相关
import { raw_execute_script, inject_file, ensure_injected, execute_script, open_tab, close_tab, create_tab_task } from './tabs.js';
export { raw_execute_script, inject_file, ensure_injected, execute_script, open_tab, close_tab, create_tab_task };
// Action 元数据相关
import { bind_action_meta } from './action_meta.js';
export { bind_action_meta };
// 通用异步工具
export function sleep_ms(ms) {
const t = Number(ms);
return new Promise((resolve) => setTimeout(resolve, Number.isFinite(t) ? Math.max(0, t) : 0));
}
export async function get_tab_url(tab_id) {
return await new Promise((resolve, reject) => {
chrome.tabs.get(tab_id, (tab) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(tab && tab.url ? String(tab.url) : '');
});
});
}
// 便捷的统一导出对象(可选使用)
export const Libs = {
// 响应处理
response: {
ok: ok_response,
fail: fail_response,
code: response_code,
guard: guard_sync
},
// Tab 操作
tabs: {
rawExecuteScript: raw_execute_script,
injectFile: inject_file,
ensureInjected: ensure_injected,
executeScript: execute_script,
open: open_tab,
close: close_tab,
createTask: create_tab_task
},
// 元数据
meta: {
bindAction: bind_action_meta
}
};
// 默认导出(可选使用)
export default Libs;

View File

@@ -1,53 +0,0 @@
// executeScriptMV2 使用 chrome.tabs.executeScript
function build_code(fn, args) {
if (typeof fn === 'function') {
if (Array.isArray(args) && args.length) {
return `(${fn.toString()}).apply(null, ${JSON.stringify(args)});`;
}
return `(${fn.toString()})();`;
}
return fn;
}
// execute_script(tabId, fn, args?, runAt?)
export function execute_script(tab_id, fn, args, run_at) {
run_at = run_at || 'document_idle';
const code = build_code(fn, args);
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(
tab_id,
{
code,
runAt: run_at,
},
(result) => {
if (chrome.runtime.lastError) {
return reject(new Error(chrome.runtime.lastError.message));
}
resolve(result);
},
);
});
}
export function inject_file(tab_id, file, run_at) {
run_at = run_at || 'document_idle';
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(
tab_id,
{
file,
runAt: run_at,
},
() => {
if (chrome.runtime.lastError) {
return reject(new Error(chrome.runtime.lastError.message));
}
resolve(true);
},
);
});
}

View File

@@ -1,19 +1,251 @@
// openTabMV2 版本(极简 + 回调风格)
// tabs.jsMV2 Tab 操作工具Promise 风格)
import { execute_script } from './inject.js';
// ──────────── Chrome API Promise 封装 ────────────
function update_tab(tab_id, update_props) {
return new Promise((resolve_update, reject_update) => {
chrome.tabs.update(tab_id, update_props, (updated_tab) => {
if (chrome.runtime.lastError) {
return reject_update(new Error(chrome.runtime.lastError.message));
}
resolve_update(updated_tab || true);
function chrome_tabs_get(tab_id) {
return new Promise((resolve, reject) => {
chrome.tabs.get(tab_id, (t) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(t);
});
});
}
function attach_tab_helpers(tab) {
function chrome_tabs_update(tab_id, props) {
return new Promise((resolve, reject) => {
chrome.tabs.update(tab_id, props, (t) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(t || true);
});
});
}
function chrome_tabs_remove(tab_id) {
return new Promise((resolve, reject) => {
chrome.tabs.remove(tab_id, () => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(true);
});
});
}
function chrome_tabs_create(opts) {
return new Promise((resolve, reject) => {
chrome.tabs.create(opts, (t) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(t);
});
});
}
function chrome_windows_create(opts) {
return new Promise((resolve, reject) => {
chrome.windows.create(opts, (w) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(w);
});
});
}
function chrome_tabs_execute_script(tab_id, details) {
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(tab_id, details, (result) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(result);
});
});
}
/**
* 等待 tab 进入 status=complete含超时
* 先检查当前状态,已 complete 则直接返回
*/
function wait_tab_status_complete(tab_id, timeout_ms = 45000) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
reject(new Error('等待页面加载超时'));
}, timeout_ms);
const listener = (id, info, tab) => {
if (id !== tab_id || info.status !== 'complete') return;
chrome.tabs.onUpdated.removeListener(listener);
clearTimeout(timer);
resolve(tab);
};
chrome.tabs.onUpdated.addListener(listener);
});
}
// ──────────── 代码构建 ────────────
const build_code = (fn, args) => {
if (typeof fn === 'function') {
const func_str = fn.toString();
if (Array.isArray(args) && args.length > 0) {
const serialized = JSON.stringify(args, (key, value) => {
if (typeof value === 'function') return undefined;
if (value && typeof value === 'object' && value.constructor === Object) {
try { JSON.stringify(value); return value; } catch { return '[Object]'; }
}
return value;
});
return `(${func_str}).apply(null, ${serialized});`;
}
return `(${func_str})();`;
}
if (typeof fn === 'string') return fn;
throw new TypeError('fn must be a function or string');
};
// ──────────── 脚本执行(低阶) ────────────
/**
* 在页面上下文执行脚本page world 桥接)
* 通过 CustomEvent + chrome.runtime.onMessage 回传结果
*/
export async function raw_execute_script(tab_id, fn, args = [], run_at = 'document_idle') {
const request_id = `${Date.now()}_${Math.random().toString().slice(2)}`;
const event_name = `__mv2_simple_page_exec_done__${request_id}`;
const page_exec_stmt = typeof fn === 'function'
? `__exec_result = ${build_code(fn, args)}`
: `__exec_result = (function () { ${fn} })();`;
const page_script_text = `
(function () {
const __request_id = ${JSON.stringify(request_id)};
const __event_name = ${JSON.stringify(event_name)};
let __exec_result;
Promise.resolve()
.then(() => {
${page_exec_stmt}
return __exec_result;
})
.then((__result) => {
window.dispatchEvent(new CustomEvent(__event_name, {
detail: { request_id: __request_id, ok: true, result: __result }
}));
})
.catch((__err) => {
window.dispatchEvent(new CustomEvent(__event_name, {
detail: {
request_id: __request_id,
ok: false,
error: {
message: (__err && __err.message) ? __err.message : String(__err),
stack: (__err && __err.stack) ? __err.stack : ''
}
}
}));
});
})();
`.trim();
const bootstrap_code = `
(function () {
const __request_id = ${JSON.stringify(request_id)};
const __event_name = ${JSON.stringify(event_name)};
const __on_done = (ev) => {
const detail = ev && ev.detail ? ev.detail : null;
if (!detail || detail.request_id !== __request_id) return;
window.removeEventListener(__event_name, __on_done, true);
try {
chrome.runtime.sendMessage({
channel: 'page_exec_bridge',
request_id: __request_id,
ok: !!detail.ok,
result: detail.result,
error_message: detail.error && detail.error.message ? detail.error.message : null,
error_stack: detail.error && detail.error.stack ? detail.error.stack : null
});
} catch (_) {}
};
window.addEventListener(__event_name, __on_done, true);
const el = document.createElement('script');
el.type = 'text/javascript';
el.textContent = ${JSON.stringify(page_script_text)};
(document.head || document.documentElement).appendChild(el);
el.parentNode && el.parentNode.removeChild(el);
})();
`.trim();
// 同时监听 onMessage 回传 + executeScript 报错,无法再简化
return await new Promise((resolve, reject) => {
const timeout_id = setTimeout(() => {
chrome.runtime.onMessage.removeListener(on_message);
reject(new Error(`Script execution timeout for tab ${tab_id}`));
}, 30000);
const on_message = (message) => {
if (!message || message.channel !== 'page_exec_bridge' || message.request_id !== request_id) return;
clearTimeout(timeout_id);
chrome.runtime.onMessage.removeListener(on_message);
if (message.ok) return resolve([message.result]);
const err = new Error(message.error_message || 'page script execution failed');
err.stack = message.error_stack || err.stack;
return reject(err);
};
chrome.runtime.onMessage.addListener(on_message);
chrome.tabs.executeScript(tab_id, { code: bootstrap_code, runAt: run_at }, () => {
if (chrome.runtime.lastError) {
clearTimeout(timeout_id);
chrome.runtime.onMessage.removeListener(on_message);
reject(new Error(chrome.runtime.lastError.message));
}
});
});
}
// ──────────── 注入文件 ────────────
export async function inject_file(tab_id, file, run_at = 'document_idle') {
await chrome_tabs_execute_script(tab_id, { file, runAt: run_at });
return true;
}
// ──────────── 确保 injected.js 已加载 ────────────
export async function ensure_injected(tab_id, max_retries = 3) {
// 先检查是否已注入
try {
const frames = await raw_execute_script(tab_id, () => !!window.__mv2_simple_injected, [], 'document_idle');
const injected = Array.isArray(frames) && frames.length ? (frames[0]?.result ?? frames[0]) : null;
if (injected === true) return true;
} catch (_) {
// 检查失败时继续尝试注入
}
let last_error;
for (let i = 1; i <= max_retries; i += 1) {
try {
await inject_file(tab_id, 'injected/injected.js', 'document_idle');
const frames = await raw_execute_script(tab_id, () => !!window.__mv2_simple_injected, [], 'document_idle');
const injected = Array.isArray(frames) && frames.length ? (frames[0]?.result ?? frames[0]) : null;
if (injected === true) return true;
if (i < max_retries) await new Promise((r) => setTimeout(r, 500 * i));
} catch (err) {
last_error = err;
if (i < max_retries) await new Promise((r) => setTimeout(r, 1000 * i));
}
}
throw new Error(`注入失败(重试 ${max_retries} 次): ${last_error?.message || 'unknown'}`);
}
// ──────────── 高阶脚本执行 ────────────
export async function execute_script(tab_id, fn, args = [], run_at = 'document_idle', options = {}) {
const opts = { ensure_injected: true, max_retries: 3, ...options };
if (opts.ensure_injected) {
await ensure_injected(tab_id, opts.max_retries);
}
return await raw_execute_script(tab_id, fn, args, run_at);
}
// ──────────── Tab 辅助方法绑定 ────────────
const attach_tab_helpers = (tab) => {
if (!tab) return tab;
tab.remove = function remove(delay_ms) {
@@ -24,84 +256,45 @@ function attach_tab_helpers(tab) {
}, Math.max(0, delay_ms));
};
tab.execute_script = async function execute_script_on_tab(fn, args, run_at) {
return await execute_script(tab.id, fn, args, run_at);
tab.execute_script = (fn, args, run_at) => execute_script(tab.id, fn, args, run_at);
tab.inject_file = (file, run_at) => inject_file(tab.id, file, run_at);
tab.ensure_injected = () => ensure_injected(tab.id);
tab.navigate = async (url, options) => {
const active = options && options.active === true;
return await chrome_tabs_update(tab.id, { url: String(url), active });
};
tab.navigate = async function navigate(url, options) {
const nav_options = options && typeof options === 'object' ? options : {};
const active = Object.prototype.hasOwnProperty.call(nav_options, 'active') ? nav_options.active === true : true;
const update_props = { url: String(url), active };
return await update_tab(tab.id, update_props);
};
/**
* 等待 tab 页面加载完成status=complete
* - 作为 tab 方法,避免业务层到处传 tab_id
*/
tab.wait_complete = function wait_complete(timeout_ms) {
tab.wait_complete = async function wait_complete(timeout_ms) {
const timeout = Number.isFinite(timeout_ms) ? Math.max(0, timeout_ms) : 45000;
return new Promise((resolve_wait, reject_wait) => {
chrome.tabs.get(tab.id, (tab0) => {
if (!chrome.runtime.lastError && tab0 && tab0.status === 'complete') {
return resolve_wait(tab0);
}
const on_updated = (updated_tab_id, change_info, updated_tab) => {
if (updated_tab_id !== tab.id) return;
if (!change_info || change_info.status !== 'complete') return;
chrome.tabs.onUpdated.removeListener(on_updated);
resolve_wait(updated_tab || true);
};
chrome.tabs.onUpdated.addListener(on_updated);
setTimeout(() => {
chrome.tabs.onUpdated.removeListener(on_updated);
reject_wait(new Error('等待页面加载超时'));
}, timeout);
});
});
const t0 = await chrome_tabs_get(tab.id).catch(() => null);
if (t0 && t0.status === 'complete') return t0;
return await wait_tab_status_complete(tab.id, timeout);
};
/**
* 你期望的风格tab.on_update_complete(() => tab.execute_script(...))
* - 每次页面刷新/导航完成(status=complete) 都会触发回调
* - 回调里可直接使用 tab.execute_script而不是外部注入器封装
*/
tab._on_update_complete_listener = null;
tab.on_update_complete = function on_update_complete(fn, options) {
if (typeof fn !== 'function') return false;
if (!tab.id) return false;
if (typeof fn !== 'function' || !tab.id) return false;
tab.off_update_complete && tab.off_update_complete();
let running = false;
const once = !!(options && options.once === true);
const on_error = options && typeof options.on_error === 'function' ? options.on_error : null;
const listener = async (updated_tab_id, change_info, updated_tab) => {
if (updated_tab_id !== tab.id) return;
if (!change_info || change_info.status !== 'complete') return;
if (updated_tab_id !== tab.id || !change_info || change_info.status !== 'complete') return;
if (running) return;
running = true;
const tab_obj = attach_tab_helpers(updated_tab || tab);
try {
await fn(tab_obj, change_info);
if (once) {
tab.off_update_complete && tab.off_update_complete();
}
} catch (err) {
if (on_error) {
on_error(err, tab_obj, change_info);
} else {
// eslint-disable-next-line no-console
console.warn('[tab_on_update] fail', { tab_id: tab.id, error: (err && err.message) || String(err) });
}
} finally {
running = false;
}
await fn(tab_obj, change_info);
if (once) tab.off_update_complete && tab.off_update_complete();
running = false;
};
chrome.tabs.onUpdated.addListener(listener);
tab._on_update_complete_listener = listener;
// 注册时如果已 complete立即触发一次,保证首屏也能执行注入
// 注册时如果已 complete立即触发一次
chrome.tabs.get(tab.id, (t0) => {
if (chrome.runtime.lastError) return;
if (t0 && t0.status === 'complete') {
@@ -111,11 +304,21 @@ function attach_tab_helpers(tab) {
return true;
};
tab.wait_update_complete_once = function wait_update_complete_once(worker) {
return new Promise((resolve, reject) => {
tab.on_update_complete(async () => {
try {
resolve(await worker(tab));
} catch (err) {
reject(err);
}
}, { once: true });
});
};
tab.off_update_complete = function off_update_complete() {
if (!tab._on_update_complete_listener) return;
try {
chrome.tabs.onUpdated.removeListener(tab._on_update_complete_listener);
} catch (_) { }
try { chrome.tabs.onUpdated.removeListener(tab._on_update_complete_listener); } catch (_) {}
tab._on_update_complete_listener = null;
};
@@ -130,55 +333,33 @@ function attach_tab_helpers(tab) {
};
return tab;
}
};
export function open_tab(url, options) {
// 保留原本 Promise 版本(内部复用)
options = options && typeof options === 'object' ? options : {};
// ──────────── 打开标签页 ────────────
return new Promise((resolve, reject) => {
chrome.tabs.create(
{
url: 'about:blank',
active: options.active !== false,
},
(tab) => {
if (chrome.runtime.lastError) {
return reject(new Error(chrome.runtime.lastError.message));
}
if (!tab || !tab.id) {
return reject(new Error('tab 创建失败'));
}
const tab_id = tab.id;
const on_updated = (updated_tab_id, change_info, updated_tab) => {
if (updated_tab_id !== tab_id) return;
if (change_info.status !== 'complete') return;
chrome.tabs.onUpdated.removeListener(on_updated);
resolve({ tab_id, tab: attach_tab_helpers(updated_tab) });
};
chrome.tabs.onUpdated.addListener(on_updated);
update_tab(tab_id, { url })
.catch((err) => {
chrome.tabs.onUpdated.removeListener(on_updated);
reject(err);
});
},
);
export async function open_tab(url, options = {}) {
const opts = { active: true, timeout: 45000, loadInBackground: false, ...options };
const tab = await chrome_tabs_create({
url: 'about:blank',
active: !opts.loadInBackground && opts.active,
});
if (!tab || !tab.id) throw new Error('创建标签页失败');
await chrome_tabs_update(tab.id, { url });
const done_tab = await wait_tab_status_complete(tab.id, opts.timeout);
return { tab_id: tab.id, tab: attach_tab_helpers(done_tab) };
}
export function close_tab(tab_id, delay_ms) {
delay_ms = Number.isFinite(delay_ms) ? delay_ms : 0;
setTimeout(() => {
chrome.tabs.remove(tab_id, () => void 0);
}, Math.max(0, delay_ms));
// ──────────── 关闭标签页 ────────────
export async function close_tab(tab_id, delay_ms = 0) {
if (delay_ms > 0) {
await new Promise((r) => setTimeout(r, delay_ms));
}
return await chrome_tabs_remove(tab_id);
}
// openTab 任务对象:用对象绑定方法,减少重复参数
// ──────────── Tab 任务对象 ────────────
export function create_tab_task(url) {
const task = {
url,
@@ -189,69 +370,38 @@ export function create_tab_task(url) {
height: 900,
target: null,
active: true,
// 你期望的写法tab_task.on_updated = () => {}
on_error: null,
on_updated: null,
set_bounds(bounds) {
bounds = bounds && typeof bounds === 'object' ? bounds : {};
if (Object.prototype.hasOwnProperty.call(bounds, 'top')) this.top = bounds.top;
if (Object.prototype.hasOwnProperty.call(bounds, 'left')) this.left = bounds.left;
if (Object.prototype.hasOwnProperty.call(bounds, 'width')) this.width = bounds.width;
if (Object.prototype.hasOwnProperty.call(bounds, 'height')) this.height = bounds.height;
return this;
},
set_target(target) {
this.target = target || null;
return this;
},
set_latest(latest) {
this.latest = !!latest;
return this;
},
set_active(active) {
this.active = active !== false;
if ('top' in bounds) this.top = bounds.top;
if ('left' in bounds) this.left = bounds.left;
if ('width' in bounds) this.width = bounds.width;
if ('height' in bounds) this.height = bounds.height;
return this;
},
set_target(target) { this.target = target || null; return this; },
set_latest(latest) { this.latest = !!latest; return this; },
set_active(active) { this.active = active !== false; return this; },
async open_async() {
// 用 chrome.windows.create 新开窗口承载 tab
const win = await new Promise((resolve, reject) => {
chrome.windows.create(
{
url: 'about:blank',
type: 'popup',
focused: true,
top: this.top,
left: this.left,
width: this.width,
height: this.height,
},
(w) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
resolve(w);
},
);
const win = await chrome_windows_create({
url: 'about:blank',
type: 'popup',
focused: true,
top: this.top,
left: this.left,
width: this.width,
height: this.height,
});
const tab0 = win && win.tabs && win.tabs[0] ? win.tabs[0] : null;
if (!tab0 || !tab0.id) {
throw new Error('popup window 创建失败');
}
if (!tab0 || !tab0.id) throw new Error('popup window 创建失败');
await update_tab(tab0.id, { url: this.url, active: this.active !== false });
const tab_done = await new Promise((resolve) => {
const on_updated = (tab_id, change_info, tab) => {
if (tab_id !== tab0.id) return;
if (change_info.status !== 'complete') return;
chrome.tabs.onUpdated.removeListener(on_updated);
resolve(tab);
};
chrome.tabs.onUpdated.addListener(on_updated);
});
return attach_tab_helpers(tab_done);
await chrome_tabs_update(tab0.id, { url: this.url, active: this.active !== false });
const done_tab = await wait_tab_status_complete(tab0.id);
return attach_tab_helpers(done_tab);
},
};
return task;
}

View File

@@ -5,6 +5,7 @@
"description": "MV2 极简骨架openTab + executeScript + __REQUEST_DONE 监听",
"permissions": [
"tabs",
"storage",
"<all_urls>"
],
"background": {
@@ -20,7 +21,8 @@
}
],
"web_accessible_resources": [
"content/request_watcher.js"
"content/request_watcher.js",
"injected/injected.js"
],
"browser_action": {
"default_title": "mv2_simple_crx"

View File

@@ -1,9 +1,9 @@
const out = document.getElementById('out');
const btn = document.getElementById('btn');
function set_out(obj) {
const set_out = (obj) => {
out.textContent = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2);
}
};
btn.addEventListener('click', () => {
set_out('执行中...');

View File

@@ -83,6 +83,22 @@ body {
font-size: 12px;
}
.label_row {
display: flex;
align-items: flex-start;
gap: 8px;
margin-top: 10px;
font-size: 12px;
color: var(--text);
line-height: 1.5;
cursor: pointer;
}
.label_row input {
margin-top: 3px;
flex-shrink: 0;
}
.input,
.textarea {
width: 100%;
@@ -159,6 +175,15 @@ body {
overflow: auto;
}
/* 响应区:不显示滚动条,长行自动换行(含无空格长串) */
.pre_response {
overflow: visible;
overflow-x: hidden;
white-space: pre-wrap;
overflow-wrap: anywhere;
word-break: break-word;
}
.pre_scroll {
max-height: 520px;
overflow: auto;

View File

@@ -20,6 +20,10 @@
<div class="card_title">调用</div>
<div class="form">
<div>
<button id="btn_bg_reload" class="btn">刷新后台</button>
</div>
<label class="label">方法名action</label>
<!-- action 列表:由 background 注册;这里仅提供快速手动调用入口 -->
<select id="action_name" class="input">
@@ -36,10 +40,12 @@
<div id="action_params_desc" class="hint" style="margin-top:6px; white-space:pre-wrap;"></div>
<textarea id="action_params" class="textarea" spellcheck="false">{}</textarea>
<label class="label_row"><input type="checkbox" id="opt_keep_tab_open" checked /> 执行后保留自动化窗口keep_tab_open覆盖下方 JSON 与本 action 默认值)</label>
<div class="row">
<button id="btn_run" class="btn primary">执行</button>
<button id="btn_clear" class="btn">清空日志</button>
<button id="btn_bg_reload" class="btn">刷新后台</button>
</div>
<div class="hint">
@@ -54,7 +60,7 @@
<label class="label">动作日志</label>
<pre id="action_log" class="pre pre_small"></pre>
<div class="card_title">响应</div>
<pre id="last_response" class="pre"></pre>
<pre id="last_response" class="pre pre_response"></pre>
</div>
</div>
</div>

View File

@@ -6,24 +6,25 @@ const btn_clear_el = document.getElementById('btn_clear');
const btn_bg_reload_el = document.getElementById('btn_bg_reload');
const last_response_el = document.getElementById('last_response');
const action_log_el = document.getElementById('action_log');
const opt_keep_tab_open_el = document.getElementById('opt_keep_tab_open');
let actions_meta = {};
const ui_state = { last_result: null, actions: [] };
function now_time() {
const now_time = () => {
const d = new Date();
const pad = (n) => String(n).padStart(2, '0');
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
};
function safe_json_parse(text) {
const safe_json_parse = (text) => {
try {
return JSON.parse(text);
} catch (e) {
return { __parse_error: e.message, __raw: text };
}
}
};
function pick_main_result(res) {
const pick_main_result = (res) => {
// 右侧只展示最核心的数据,避免被 ok/request_id 包裹层干扰
if (res && res.ok && res.data) {
// 约定action 返回的核心结果放在 data.result例如 amazon_search_list 的 stage=list
@@ -31,14 +32,14 @@ function pick_main_result(res) {
return res.data;
}
return res;
}
};
function render_state() {
const render_state = () => {
last_response_el.textContent = JSON.stringify(ui_state.last_result, null, 2);
action_log_el.textContent = ui_state.actions.join('\n');
}
};
function push_action(obj) {
const push_action = (obj) => {
// 动作日志只保留单行文本,避免 JSON 换行太长
const ts = now_time();
const type = obj && obj.type ? String(obj.type) : 'action';
@@ -64,11 +65,16 @@ function push_action(obj) {
ui_state.actions.splice(0, ui_state.actions.length - 200);
}
render_state();
}
};
const apply_keep_tab_open_override = (parsed) => {
if (!opt_keep_tab_open_el || !parsed || typeof parsed !== 'object' || parsed.__parse_error) return parsed;
return { ...parsed, keep_tab_open: opt_keep_tab_open_el.checked === true };
};
btn_run_el.addEventListener('click', () => {
const action = action_name_el.value;
const params = safe_json_parse(action_params_el.value || '{}');
const params = apply_keep_tab_open_override(safe_json_parse(action_params_el.value || '{}'));
push_action({ type: 'call', action, params });
ui_state.last_result = { running: true, action, params };

View File

@@ -25,4 +25,4 @@ await start_all_cron_tasks();
app.listen(port);
// eslint-disable-next-line no-console
console.log(`server listening on ${port}`);
console.log(`[${new Date().toLocaleString()}] server listening on ${port}`);

View File

@@ -15,11 +15,11 @@ export function get_sequelize_options() {
? (sql, timing_ms) => {
if (cfg.crawler.log_sql_benchmark === true && typeof timing_ms === 'number') {
// eslint-disable-next-line no-console
console.log('[sql]', { timing_ms, sql });
console.log(`[${new Date().toLocaleString()}] [sql]`, { timing_ms, sql });
return;
}
// eslint-disable-next-line no-console
console.log('[sql]', sql);
console.log(`[${new Date().toLocaleString()}] [sql]`, sql);
}
: false,
define: {

View File

@@ -2,5 +2,5 @@ import { sequelize } from '../models/index.js';
await sequelize.sync({ alter: true });
// eslint-disable-next-line no-console
console.log('sync ok');
console.log(`[${new Date().toLocaleString()}] sync ok`);
await sequelize.close();

View File

@@ -186,6 +186,8 @@ export async function run_amazon_search_detail_reviews_flow(flow_payload) {
await sleep_ms(1000);
const list_payload = { category_keyword, limit };
if (sort_by) {
list_payload.sort_by = sort_by;

View File

@@ -115,7 +115,7 @@ export async function invoke_extension_action(action_name, action_payload, optio
const log_enabled = cfg.crawler.log_invoke_action;
if (log_enabled) {
// eslint-disable-next-line no-console
console.log('[invoke_extension_action] start', {
console.log(`[${new Date().toLocaleString()}] [invoke_extension_action] start`, {
action_name,
has_payload: !!action_payload,
keys: action_payload && typeof action_payload === 'object' ? Object.keys(action_payload).slice(0, 20) : []
@@ -178,14 +178,17 @@ export async function invoke_extension_action(action_name, action_payload, optio
if (log_enabled) {
// eslint-disable-next-line no-console
console.log('[invoke_extension_action] ok', { action_name, cost_ms: Date.now() - started_at });
console.log(`[${new Date().toLocaleString()}] [invoke_extension_action] ok`, {
action_name,
cost_ms: Date.now() - started_at
});
}
return action_res;
} catch (err) {
if (log_enabled) {
// eslint-disable-next-line no-console
console.log('[invoke_extension_action] fail', {
console.log(`[${new Date().toLocaleString()}] [invoke_extension_action] fail`, {
action_name,
cost_ms: Date.now() - started_at,
error: (err && err.message) || String(err)

View File

@@ -43,7 +43,7 @@ async function run_cron_task(task) {
async function run_cron_task_with_guard(task_name, task) {
if (running_task_name_set.has(task_name)) {
// eslint-disable-next-line no-console
console.log('[cron] skip (already running)', { name: task_name });
console.log(`[${new Date().toLocaleString()}] [cron] skip (already running)`, { name: task_name });
return;
}
@@ -51,7 +51,8 @@ async function run_cron_task_with_guard(task_name, task) {
try {
await run_cron_task(task);
} catch (error) {
console.warn('[cron] error', { task_name, error });
// eslint-disable-next-line no-console
console.warn(`[${new Date().toLocaleString()}] [cron] error`, { task_name, error });
} finally {
running_task_name_set.delete(task_name);
}
@@ -66,13 +67,14 @@ export async function start_all_cron_tasks() {
const job = cron.schedule(task.cron_expression, async () => {
await run_cron_task_with_guard(task_name, task);
});
console.log('job', { task_name, });
// eslint-disable-next-line no-console
console.log(`[${new Date().toLocaleString()}] job`, { task_name });
cron_jobs.push(job);
if (run_now) {
// 启动时额外立刻跑一次(仍走 guard避免与 cron 触发撞车)
// eslint-disable-next-line no-console
console.log('[cron] run_now', { task_name });
console.log(`[${new Date().toLocaleString()}] [cron] run_now`, { task_name });
await run_cron_task_with_guard(task_name, task);
}
}