Compare commits
6 Commits
54cd6ea9ae
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7164dc3ed5 | |||
|
|
6200fcc66f | ||
|
|
7ba462aedd | ||
|
|
873fd436b1 | ||
|
|
66df49a7c3 | ||
|
|
a776873477 |
163
mv2_simple_crx/src/README.md
Normal file
163
mv2_simple_crx/src/README.md
Normal 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 注释提高代码可读性
|
||||||
|
- 定期检查和优化导出结构
|
||||||
@@ -1,73 +1,68 @@
|
|||||||
// Amazon:action(编排逻辑放这里),注入函数放 amazon_tool.js
|
import { create_tab_task, ok_response, fail_response, guard_sync, response_code, sleep_ms, get_tab_url } from '../libs/index.js';
|
||||||
|
|
||||||
import { create_tab_task } from '../libs/tabs.js';
|
|
||||||
import { fail_response, ok_response, response_code } from '../libs/action_response.js';
|
|
||||||
import {
|
import {
|
||||||
injected_amazon_homepage_search,
|
injected_amazon_validate_captcha_continue,
|
||||||
injected_amazon_product_detail,
|
injected_amazon_product_detail,
|
||||||
injected_amazon_product_reviews,
|
injected_amazon_product_reviews,
|
||||||
injected_amazon_search_list,
|
|
||||||
injected_amazon_switch_language,
|
injected_amazon_switch_language,
|
||||||
injected_amazon_validate_captcha_continue,
|
injected_amazon_search_list,
|
||||||
|
injected_amazon_homepage_search,
|
||||||
|
injected_detect_captcha_page,
|
||||||
normalize_product_url,
|
normalize_product_url,
|
||||||
|
pick_first_script_result,
|
||||||
try_solve_amazon_validate_captcha,
|
try_solve_amazon_validate_captcha,
|
||||||
wait_until_search_list_url,
|
wait_until_search_list_url,
|
||||||
} from './amazon_tool.js';
|
} 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¤cy=HKD';
|
||||||
const AMAZON_ZH_HOME_URL = 'https://www.amazon.com/-/zh/ref=nav_logo';
|
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¤cy=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 = {
|
const create_send_action = (sendResponse) => (action_name, response) => {
|
||||||
|
sendResponse({ action: action_name, ...response });
|
||||||
|
};
|
||||||
|
|
||||||
|
const SORT_MAP = {
|
||||||
featured: 'relevanceblender',
|
featured: 'relevanceblender',
|
||||||
review: 'review-rank',
|
review: 'review-rank',
|
||||||
newest: 'date-desc-rank',
|
newest: 'date-desc-rank',
|
||||||
price_asc: 'price-asc-rank',
|
price_asc: 'price-asc-rank',
|
||||||
price_desc: 'price-desc-rank',
|
price_desc: 'price-desc-rank',
|
||||||
bestseller: 'exact-aware-popularity-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) => {
|
function parse_limit(data, default_val, max_val) {
|
||||||
if (typeof sendResponse === 'function') {
|
const n = data && Object.prototype.hasOwnProperty.call(data, 'limit') ? Number(data.limit) : default_val;
|
||||||
sendResponse({ action, data: payload });
|
if (!Number.isFinite(n)) return default_val;
|
||||||
sendResponse.log && sendResponse.log(payload);
|
return Math.max(1, Math.min(max_val, Math.floor(n)));
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const tab_task = create_tab_task(AMAZON_ZH_HOME_URL)
|
// ──────────── 核心业务函数(从 handler 回调中提取) ────────────
|
||||||
.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 () => {
|
async function do_search_list(tab, { keyword, sort_s, category_keyword, sort_by, limit }) {
|
||||||
await tab.execute_script(injected_amazon_search_list, [{ category_keyword, sort_by, debug: true }], 'document_idle');
|
// 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);
|
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);
|
// 首页搜索
|
||||||
|
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();
|
await tab.wait_complete();
|
||||||
|
|
||||||
|
// 排序
|
||||||
if (sort_s) {
|
if (sort_s) {
|
||||||
const u = new URL(url);
|
const u = new URL(url);
|
||||||
u.searchParams.set('s', sort_s);
|
u.searchParams.set('s', sort_s);
|
||||||
@@ -76,6 +71,7 @@ export function amazon_search_list(data, sendResponse) {
|
|||||||
await tab.wait_complete();
|
await tab.wait_complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 分页抓取
|
||||||
const unique_map = new Map();
|
const unique_map = new Map();
|
||||||
let next_url = url;
|
let next_url = url;
|
||||||
for (let page = 1; page <= 10 && unique_map.size < limit; page += 1) {
|
for (let page = 1; page <= 10 && unique_map.size < limit; page += 1) {
|
||||||
@@ -83,276 +79,226 @@ export function amazon_search_list(data, sendResponse) {
|
|||||||
await tab.navigate(next_url);
|
await tab.navigate(next_url);
|
||||||
await tab.wait_complete();
|
await tab.wait_complete();
|
||||||
}
|
}
|
||||||
const injected_result_list = await tab.execute_script(
|
const raw = await tab.execute_script(injected_amazon_search_list, [{ url: next_url, category_keyword, sort_by }], 'document_idle');
|
||||||
injected_amazon_search_list,
|
const result = pick_first_script_result(raw);
|
||||||
[{ url: next_url, category_keyword, sort_by }],
|
const items = result && Array.isArray(result.items) ? result.items : [];
|
||||||
'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) => {
|
items.forEach((it) => {
|
||||||
const k = it && (it.asin || it.url) ? String(it.asin || it.url) : null;
|
const k = it && (it.asin || it.url) ? String(it.asin || it.url) : null;
|
||||||
if (!k) return;
|
if (k && !unique_map.has(k)) unique_map.set(k, it);
|
||||||
if (!unique_map.has(k)) unique_map.set(k, it);
|
|
||||||
});
|
});
|
||||||
if (unique_map.size >= limit) break;
|
if (unique_map.size >= limit) break;
|
||||||
next_url = injected_result && injected_result.next_url ? String(injected_result.next_url) : null;
|
next_url = result && result.next_url ? String(result.next_url) : null;
|
||||||
if (!next_url) break;
|
if (!next_url) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const list_result = { stage: 'list', limit, total: unique_map.size, items: Array.from(unique_map.values()).slice(0, limit) };
|
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 });
|
return { 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: '野餐包' },
|
*/
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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' },
|
sort_by: { type: 'string', desc: '排序方式:featured / price_asc / price_desc / review / newest / bestseller', default: 'featured' },
|
||||||
limit: { type: 'number', desc: '抓取数量上限(默认 100,最大 200)', default: 100 },
|
limit: { type: 'number', desc: '抓取数量上限(默认 100,最大 200)', default: 100 },
|
||||||
keep_tab_open: { type: 'boolean', desc: '调试用:不自动关闭窗口,方便手动刷新观察轨迹', default: false },
|
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] || '';
|
||||||
|
|
||||||
export function amazon_set_language(data, sendResponse) {
|
const tab_task = create_tab_task(AMAZON_ZH_HOME_URL)
|
||||||
return new Promise((resolve, reject) => {
|
.set_latest(false)
|
||||||
const mapping = {
|
.set_bounds({ top: 20, left: 20, width: 1440, height: 900 })
|
||||||
EN: 'en_US',
|
.set_target('__amazon_search_list');
|
||||||
ES: 'es_US',
|
|
||||||
AR: 'ar_AE',
|
let tab = null;
|
||||||
DE: 'de_DE',
|
try {
|
||||||
HE: 'he_IL',
|
tab = await tab_task.open_async();
|
||||||
KO: 'ko_KR',
|
const payload = await tab.wait_update_complete_once(() =>
|
||||||
PT: 'pt_BR',
|
do_search_list(tab, { keyword, sort_s, category_keyword, sort_by, limit })
|
||||||
ZH_CN: 'zh_CN',
|
);
|
||||||
ZH_TW: 'zh_TW',
|
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 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 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)
|
const tab_task = create_tab_task(AMAZON_HOME_FOR_LANG)
|
||||||
.set_latest(false)
|
.set_latest(false)
|
||||||
.set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
|
.set_bounds({ top: 20, left: 20, width: 1280, height: 900 });
|
||||||
tab_task.open_async()
|
|
||||||
.then((tab) => {
|
try {
|
||||||
tab.on_update_complete(async () => {
|
const tab = await tab_task.open_async();
|
||||||
// 首次 complete 也会触发:在回调里完成注入与结果采集
|
const payload = await tab.wait_update_complete_once(() => do_set_language(tab, code));
|
||||||
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
|
send_action('amazon_set_language', ok_response(payload));
|
||||||
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);
|
tab.remove(0);
|
||||||
}, {
|
return payload;
|
||||||
once: true,
|
} catch (err) {
|
||||||
on_error: (err) => {
|
|
||||||
send_action('amazon_set_language', fail_response((err && err.message) || String(err), {
|
send_action('amazon_set_language', fail_response((err && err.message) || String(err), {
|
||||||
code: response_code.runtime_error,
|
code: response_code.runtime_error,
|
||||||
documentURI: AMAZON_HOME_FOR_LANG,
|
documentURI: AMAZON_HOME_FOR_LANG,
|
||||||
}));
|
}));
|
||||||
reject(err);
|
throw 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),切换购物界面语言';
|
name: 'amazon_product_detail',
|
||||||
amazon_set_language.params = {
|
desc: 'Amazon 商品详情(标题、价格、品牌、要点、配送摘要等)',
|
||||||
lang: { type: 'string', desc: 'EN / ES / AR / DE / HE / KO / PT / ZH_CN(默认) / ZH_TW', default: 'ZH_CN' },
|
params: {
|
||||||
};
|
|
||||||
|
|
||||||
export function amazon_product_detail(data, sendResponse) {
|
|
||||||
return run_pdp_action(data && data.product_url, injected_amazon_product_detail, [], 'amazon_product_detail', sendResponse);
|
|
||||||
}
|
|
||||||
|
|
||||||
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' },
|
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 });
|
||||||
|
|
||||||
export function amazon_product_reviews(data, sendResponse) {
|
try {
|
||||||
const limit = data && data.limit != null ? Number(data.limit) : 50;
|
const tab = await tab_task.open_async();
|
||||||
return run_pdp_action(data && data.product_url, injected_amazon_product_reviews, [{ limit }], 'amazon_product_reviews', sendResponse);
|
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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
amazon_product_reviews.desc = 'Amazon 商品页买家评论(详情页 [data-hook=review],条数受页面展示限制)';
|
{
|
||||||
amazon_product_reviews.params = {
|
name: 'amazon_product_reviews',
|
||||||
|
desc: 'Amazon 商品页买家评论',
|
||||||
|
params: {
|
||||||
product_url: { type: 'string', desc: '商品详情页完整 URL', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
|
product_url: { type: 'string', desc: '商品详情页完整 URL', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
|
||||||
limit: { type: 'number', desc: '最多条数(默认 50,上限 100)', default: 50 },
|
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: [] });
|
|
||||||
}
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
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);
|
|
||||||
},
|
},
|
||||||
});
|
handler: async (data, sendResponse) => {
|
||||||
})
|
const send_action = create_send_action(sendResponse);
|
||||||
.catch((err) => {
|
const normalized = guard_sync(() => normalize_product_url(data && data.product_url));
|
||||||
const is_bad_request = (err && err.message) === '缺少 product_url'
|
if (!normalized.ok) {
|
||||||
|| (err && err.message) === 'product_url 需为亚马逊域名'
|
send_action('amazon_product_reviews', fail_response((normalized.error && normalized.error.message) || String(normalized.error), { code: response_code.bad_request }));
|
||||||
|| (err && err.message) === 'product_url 需包含 /dp/ASIN 或 /gp/product/ASIN';
|
return;
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
};
|
const url = normalized.data;
|
||||||
return new Promise((resolve, reject) => {
|
const limit = parse_limit(data, 50, 100);
|
||||||
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 });
|
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 = {};
|
try {
|
||||||
for (const step of steps || []) {
|
const tab = await tab_task.open_async();
|
||||||
if (!step || !step.name || typeof step.injected_fn !== 'function') continue;
|
const payload = await tab.wait_update_complete_once(() =>
|
||||||
const raw_list = await tab.execute_script(step.injected_fn, step.inject_args || [], 'document_idle');
|
do_pdp_steps(tab, url, [{ name: 'reviews', injected_fn: injected_amazon_product_reviews, inject_args: [{ limit }] }])
|
||||||
const result = Array.isArray(raw_list) ? raw_list[0] : raw_list;
|
);
|
||||||
results[step.name] = result;
|
send_action('amazon_product_reviews', ok_response(payload));
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
tab.remove(0);
|
||||||
}, {
|
return payload;
|
||||||
once: true,
|
} catch (err) {
|
||||||
on_error: (err) => {
|
send_action('amazon_product_reviews', fail_response((err && err.message) || String(err), { code: response_code.runtime_error, documentURI: url }));
|
||||||
send_action(action_name, fail_response((err && err.message) || String(err), {
|
throw 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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
amazon_product_detail_reviews.desc = 'Amazon 商品详情 + 评论(同一详情页,支持 skip_detail=true)';
|
{
|
||||||
amazon_product_detail_reviews.params = {
|
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' },
|
product_url: { type: 'string', desc: '商品详情页完整 URL(含 /dp/ASIN)', default: 'https://www.amazon.com/-/zh/dp/B0B56CHMSC' },
|
||||||
limit: { type: 'number', desc: '最多评论条数(默认 50,上限 100)', default: 50 },
|
limit: { type: 'number', desc: '最多评论条数(默认 50,上限 100)', default: 50 },
|
||||||
skip_detail: { type: 'boolean', desc: '当日已拉过详情则跳过详情提取', default: false },
|
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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|||||||
@@ -1,70 +1,43 @@
|
|||||||
// Amazon:注入函数 + action 实现(amazon.js 仅保留 action 壳)
|
import { sleep_ms, get_tab_url } from '../libs/index.js';
|
||||||
|
|
||||||
|
// Amazon:页面注入函数 + 纯工具
|
||||||
//
|
//
|
||||||
// 约定:
|
// 约定:
|
||||||
// - injected_* 在页面上下文执行,只依赖 DOM
|
// - 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() {
|
export function injected_amazon_validate_captcha_continue() {
|
||||||
const href = location.href || '';
|
const injected_utils = () => window.__mv2_simple_injected || null;
|
||||||
const is_captcha = href.includes('/errors/validateCaptcha');
|
const dispatch_human_click = (target_el) => {
|
||||||
if (!is_captcha) return { ok: true, is_captcha: false, clicked: false, href };
|
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 =
|
const btn =
|
||||||
document.querySelector('form[action="/errors/validateCaptcha"] button[type="submit"].a-button-text') ||
|
form.querySelector('button[type="submit"].a-button-text') ||
|
||||||
document.querySelector('form[action*="validateCaptcha"] input[type="submit"]') ||
|
form.querySelector('input[type="submit"]') ||
|
||||||
document.querySelector('form[action*="validateCaptcha"] button[type="submit"]') ||
|
form.querySelector('button[type="submit"]') ||
|
||||||
document.querySelector('input[type="submit"][value*="Continue"]') ||
|
document.querySelector('input[type="submit"][value*="Continue"]') ||
|
||||||
document.querySelector('button[type="submit"]');
|
document.querySelector('button[type="submit"]');
|
||||||
|
|
||||||
const clicked = btn ? dispatch_human_click(btn) : false;
|
const clicked = btn ? dispatch_human_click(btn) : false;
|
||||||
if (!clicked) {
|
if (!clicked) {
|
||||||
const form = document.querySelector('form[action*="validateCaptcha"]');
|
|
||||||
if (form) {
|
|
||||||
try {
|
try {
|
||||||
form.submit();
|
form.submit();
|
||||||
return { ok: true, is_captcha: true, clicked: true, method: 'submit', href };
|
return { ok: true, is_captcha: true, clicked: true, method: 'submit', href: location.href };
|
||||||
} catch (_) { }
|
} 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) {
|
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');
|
return tab_url.includes('amazon.') && tab_url.includes('/errors/validateCaptcha');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sleep_ms(ms) {
|
/**
|
||||||
const t = Number(ms);
|
* 基于 DOM 特征检测验证码页(注入到页面执行)
|
||||||
return new Promise((resolve) => setTimeout(resolve, Number.isFinite(t) ? Math.max(0, t) : 0));
|
*/
|
||||||
|
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) {
|
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;
|
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) {
|
for (let i = 0; i < rounds; i += 1) {
|
||||||
const tab_state = await new Promise((resolve) => {
|
const url = await get_tab_url(tab.id).catch(() => '');
|
||||||
chrome.tabs.get(tab.id, (t) => resolve(t || null));
|
|
||||||
});
|
|
||||||
const url = tab_state && tab_state.url ? String(tab_state.url) : '';
|
|
||||||
if (!is_amazon_validate_captcha_url(url)) return true;
|
if (!is_amazon_validate_captcha_url(url)) return true;
|
||||||
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
|
await tab.execute_script(injected_amazon_validate_captcha_continue, [], 'document_idle');
|
||||||
await sleep_ms(800 + Math.floor(Math.random() * 600));
|
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;
|
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) {
|
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() : '';
|
const keyword = params && params.keyword ? String(params.keyword).trim() : '';
|
||||||
if (!keyword) return { ok: false, error: 'empty_keyword' };
|
if (!keyword) return { ok: false, error: 'empty_keyword' };
|
||||||
|
|
||||||
function wait_query(selectors, timeout_ms) {
|
const u = injected_utils();
|
||||||
const list = Array.isArray(selectors) ? selectors : [];
|
const wait_query = u && typeof u.wait_query === 'function' ? u.wait_query : () => null;
|
||||||
const deadline = Date.now() + (Number.isFinite(timeout_ms) ? timeout_ms : 5000);
|
const set_input_value = u && typeof u.set_input_value === 'function' ? u.set_input_value : () => false;
|
||||||
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 input = wait_query([
|
const input = wait_query([
|
||||||
'#twotabsearchtextbox',
|
'#twotabsearchtextbox',
|
||||||
@@ -120,10 +107,8 @@ export function injected_amazon_homepage_search(params) {
|
|||||||
'input[type="search"][name="field-keywords"]',
|
'input[type="search"][name="field-keywords"]',
|
||||||
], 7000);
|
], 7000);
|
||||||
if (!input) return { ok: false, error: 'no_search_input' };
|
if (!input) return { ok: false, error: 'no_search_input' };
|
||||||
input.focus();
|
set_input_value(input, keyword);
|
||||||
input.value = keyword;
|
|
||||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
||||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
||||||
const btn = wait_query([
|
const btn = wait_query([
|
||||||
'#nav-search-submit-button',
|
'#nav-search-submit-button',
|
||||||
'#nav-search-bar-form input[type="submit"]',
|
'#nav-search-bar-form input[type="submit"]',
|
||||||
@@ -133,44 +118,48 @@ export function injected_amazon_homepage_search(params) {
|
|||||||
'input.nav-input[type="submit"]',
|
'input.nav-input[type="submit"]',
|
||||||
], 2000);
|
], 2000);
|
||||||
if (btn) {
|
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');
|
const form = input.form || input.closest('form');
|
||||||
if (form && typeof form.requestSubmit === 'function') {
|
if (form && typeof form.requestSubmit === 'function') {
|
||||||
form.requestSubmit();
|
try { form.requestSubmit(); return { ok: true, method: 'request_submit' }; } catch (_) {}
|
||||||
return { ok: true, method: 'request_submit' };
|
|
||||||
}
|
}
|
||||||
if (form && typeof form.submit === 'function') {
|
if (form && typeof form.submit === 'function') {
|
||||||
form.submit();
|
try { form.submit(); return { ok: true, method: 'form_submit' }; } catch (_) {}
|
||||||
return { ok: true, method: 'form_submit' };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
input.focus();
|
||||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
|
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('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 }));
|
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' };
|
return { ok: true, method: 'keyboard_enter' };
|
||||||
} catch (_) {
|
} catch (_) {}
|
||||||
// ignore and return explicit error
|
return { ok: false, error: 'submit_all_fallback_failed', keyword };
|
||||||
}
|
|
||||||
return { ok: false, error: 'no_submit', keyword };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────── 切换语言(注入) ────────────
|
||||||
|
|
||||||
export function injected_amazon_switch_language(params) {
|
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 = {
|
const mapping = {
|
||||||
EN: 'en_US',
|
EN: 'en_US', ES: 'es_US', AR: 'ar_AE', DE: 'de_DE',
|
||||||
ES: 'es_US',
|
HE: 'he_IL', KO: 'ko_KR', PT: 'pt_BR', ZH_CN: 'zh_CN', ZH_TW: 'zh_TW',
|
||||||
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 raw = params && params.lang != null ? String(params.lang).trim().toUpperCase() : 'ZH_CN';
|
||||||
const code = Object.prototype.hasOwnProperty.call(mapping, raw) ? raw : 'ZH_CN';
|
const code = Object.prototype.hasOwnProperty.call(mapping, raw) ? raw : 'ZH_CN';
|
||||||
const switch_lang = mapping[code];
|
const switch_lang = mapping[code];
|
||||||
const href_sel = `a[href="#switch-lang=${switch_lang}"]`;
|
const href_sel = `a[href="#switch-lang=${switch_lang}"]`;
|
||||||
|
const u = injected_utils();
|
||||||
|
|
||||||
const deadline = Date.now() + 6000;
|
const deadline = Date.now() + 6000;
|
||||||
let link = null;
|
let link = null;
|
||||||
while (Date.now() < deadline) {
|
while (Date.now() < deadline) {
|
||||||
@@ -179,8 +168,7 @@ export function injected_amazon_switch_language(params) {
|
|||||||
const r = link.getBoundingClientRect();
|
const r = link.getBoundingClientRect();
|
||||||
if (r.width > 0 && r.height > 0) break;
|
if (r.width > 0 && r.height > 0) break;
|
||||||
}
|
}
|
||||||
const t0 = performance.now();
|
if (u && typeof u.busy_wait_ms === 'function') u.busy_wait_ms(40);
|
||||||
while (performance.now() - t0 < 40) { }
|
|
||||||
}
|
}
|
||||||
if (!link) return { ok: false, error: 'lang_option_timeout', lang: code };
|
if (!link) return { ok: false, error: 'lang_option_timeout', lang: code };
|
||||||
dispatch_human_click(link);
|
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('input[type="submit"][aria-labelledby*="icp-save-button"]') ||
|
||||||
document.querySelector('span.icp-save-button input[type="submit"]');
|
document.querySelector('span.icp-save-button input[type="submit"]');
|
||||||
if (save) break;
|
if (save) break;
|
||||||
const t1 = performance.now();
|
if (u && typeof u.busy_wait_ms === 'function') u.busy_wait_ms(40);
|
||||||
while (performance.now() - t1 < 40) { }
|
|
||||||
}
|
|
||||||
if (save) {
|
|
||||||
dispatch_human_click(save);
|
|
||||||
}
|
}
|
||||||
|
if (save) dispatch_human_click(save);
|
||||||
|
|
||||||
return { ok: true, lang: code };
|
return { ok: true, lang: code };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────── 搜索列表(注入) ────────────
|
||||||
|
|
||||||
export function injected_amazon_search_list(params) {
|
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 : {};
|
params = params && typeof params === 'object' ? params : {};
|
||||||
const debug = params.debug === true;
|
const debug = params.debug === true;
|
||||||
|
const u = injected_utils();
|
||||||
|
|
||||||
// validateCaptcha:在 onUpdated(complete) 钩子里也能自动处理
|
// validateCaptcha 页面:直接点击继续
|
||||||
if ((location.href || '').includes('/errors/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 =
|
const btn =
|
||||||
document.querySelector('form[action="/errors/validateCaptcha"] button[type="submit"].a-button-text') ||
|
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"] input[type="submit"]') ||
|
||||||
document.querySelector('form[action*="validateCaptcha"] button[type="submit"]') ||
|
document.querySelector('form[action*="validateCaptcha"] button[type="submit"]') ||
|
||||||
document.querySelector('input[type="submit"][value*="Continue"]') ||
|
document.querySelector('input[type="submit"][value*="Continue"]') ||
|
||||||
document.querySelector('button[type="submit"]');
|
document.querySelector('button[type="submit"]');
|
||||||
const clicked = btn ? dispatch_human_click_local(btn) : false;
|
const clicked = btn ? dispatch_human_click(btn) : false;
|
||||||
if (debug) {
|
if (debug) console.log('[amazon][on_complete] validateCaptcha', { clicked, href: location.href });
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log('[amazon][on_complete] validateCaptcha', { clicked, href: location.href });
|
|
||||||
}
|
|
||||||
return { stage: 'captcha', href: location.href, clicked };
|
return { stage: 'captcha', href: location.href, clicked };
|
||||||
}
|
}
|
||||||
|
|
||||||
const start_url = params && params.url ? String(params.url) : location.href;
|
const start_url = params.url ? String(params.url) : location.href;
|
||||||
const category_keyword = params && params.category_keyword ? String(params.category_keyword).trim() : '';
|
const category_keyword = params.category_keyword ? String(params.category_keyword).trim() : '';
|
||||||
const sort_by = params && params.sort_by ? String(params.sort_by).trim() : '';
|
const sort_by = params.sort_by ? String(params.sort_by).trim() : '';
|
||||||
|
|
||||||
function pick_number(text) {
|
const abs_url = u && typeof u.abs_url === 'function' ? u.abs_url : (x) => x;
|
||||||
if (!text) return null;
|
const parse_asin_from_url = u && typeof u.parse_asin_from_url === 'function' ? u.parse_asin_from_url : () => null;
|
||||||
const s = String(text).replace(/[(),]/g, ' ').replace(/\s+/g, ' ').trim();
|
const pick_number = u && typeof u.pick_number === 'function' ? u.pick_number : () => null;
|
||||||
const m = s.match(/(\d+(?:\.\d+)?)/);
|
const pick_int = u && typeof u.pick_int === 'function' ? u.pick_int : () => null;
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
function extract_results() {
|
function extract_results() {
|
||||||
const items = [];
|
const items = [];
|
||||||
@@ -327,13 +265,8 @@ export function injected_amazon_search_list(params) {
|
|||||||
items.push({
|
items.push({
|
||||||
index: idx + 1,
|
index: idx + 1,
|
||||||
asin: asin || parse_asin_from_url(item_url),
|
asin: asin || parse_asin_from_url(item_url),
|
||||||
title,
|
title, url: item_url, price,
|
||||||
url: item_url,
|
rating, rating_text, review_count, review_count_text,
|
||||||
price,
|
|
||||||
rating,
|
|
||||||
rating_text,
|
|
||||||
review_count,
|
|
||||||
review_count_text,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return items;
|
return items;
|
||||||
@@ -342,40 +275,32 @@ export function injected_amazon_search_list(params) {
|
|||||||
function pick_next_url() {
|
function pick_next_url() {
|
||||||
const a = document.querySelector('a.s-pagination-next');
|
const a = document.querySelector('a.s-pagination-next');
|
||||||
if (!a) return null;
|
if (!a) return null;
|
||||||
const aria_disabled = (a.getAttribute('aria-disabled') || '').trim().toLowerCase();
|
if ((a.getAttribute('aria-disabled') || '').trim().toLowerCase() === 'true') return null;
|
||||||
if (aria_disabled === 'true') return null;
|
|
||||||
if (a.classList && a.classList.contains('s-pagination-disabled')) return null;
|
if (a.classList && a.classList.contains('s-pagination-disabled')) return null;
|
||||||
const href = a.getAttribute('href');
|
const href = a.getAttribute('href');
|
||||||
if (!href) return null;
|
return href ? abs_url(href) : null;
|
||||||
return abs_url(href);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = extract_results();
|
const items = extract_results();
|
||||||
const out = { start_url, href: location.href, category_keyword, sort_by, total: items.length, items, next_url: pick_next_url() };
|
const out = { start_url, href: location.href, category_keyword, sort_by, total: items.length, items, next_url: pick_next_url() };
|
||||||
if (debug) {
|
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 });
|
||||||
console.log('[amazon][on_complete] search_list', {
|
try { window.__amazon_debug_last_search_list = out; } catch (_) {}
|
||||||
href: out.href,
|
|
||||||
total: out.total,
|
|
||||||
has_next: !!out.next_url,
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
window.__amazon_debug_last_search_list = out;
|
|
||||||
} catch (_) { }
|
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────── 商品详情(注入) ────────────
|
||||||
|
|
||||||
export function injected_amazon_product_detail() {
|
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_match = location.pathname.match(/\/(?:dp|gp\/product)\/([A-Z0-9]{10})/i);
|
||||||
const asin = asin_match ? asin_match[1].toUpperCase() : null;
|
const asin = asin_match ? asin_match[1].toUpperCase() : null;
|
||||||
|
|
||||||
const product_info = {};
|
const product_info = {};
|
||||||
function set_info(k, v, max_len) {
|
function set_info(k, v, max_len) {
|
||||||
k = norm(k);
|
k = norm(k); v = norm(v); max_len = max_len || 600;
|
||||||
v = norm(v);
|
|
||||||
max_len = max_len || 600;
|
|
||||||
if (!k || !v || k.length > 100) return;
|
if (!k || !v || k.length > 100) return;
|
||||||
if (v.length > max_len) v = v.slice(0, max_len);
|
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;
|
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);
|
if (del) delivery_hint = norm(del.innerText).slice(0, 500);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stage: 'detail',
|
stage: 'detail', asin, title, price,
|
||||||
asin,
|
brand_line, brand_store_url, rating_stars, review_count_text,
|
||||||
title,
|
ac_badge, social_proof, bestseller_hint,
|
||||||
price,
|
product_info, detail_extra_lines, bullets, delivery_hint,
|
||||||
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,
|
url: location.href,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────── 商品评论(注入) ────────────
|
||||||
|
|
||||||
export function injected_amazon_product_reviews(params) {
|
export function injected_amazon_product_reviews(params) {
|
||||||
const raw = params && params.limit != null ? Number(params.limit) : 50;
|
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;
|
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 };
|
return { stage: 'reviews', limit, total: items.length, items, url: location.href };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────── URL 工具 ────────────
|
||||||
|
|
||||||
export function normalize_product_url(u) {
|
export function normalize_product_url(u) {
|
||||||
let s = u ? String(u).trim() : '';
|
let s = u ? String(u).trim() : '';
|
||||||
if (!s) throw new Error('缺少 product_url');
|
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');
|
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);
|
* 轮询等待 tab URL 变为搜索列表页(async 循环,替代旧版回调递归)
|
||||||
return new Promise((resolve, reject) => {
|
*/
|
||||||
const tick = () => {
|
export async function wait_until_search_list_url(tab_id, timeout_ms = 45000) {
|
||||||
chrome.tabs.get(tab_id, (tab) => {
|
const deadline = Date.now() + timeout_ms;
|
||||||
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
|
while (Date.now() < deadline) {
|
||||||
const u = tab && tab.url ? tab.url : '';
|
const url = await get_tab_url(tab_id);
|
||||||
if (is_amazon_search_list_url(u)) return resolve(u);
|
if (is_amazon_search_list_url(url)) return url;
|
||||||
if (Date.now() >= deadline) return reject(new Error('等待首页搜索跳转到列表页超时'));
|
await sleep_ms(400);
|
||||||
setTimeout(tick, 400);
|
}
|
||||||
});
|
throw new Error('等待首页搜索跳转到列表页超时');
|
||||||
};
|
|
||||||
tick();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
38
mv2_simple_crx/src/actions/index.js
Normal file
38
mv2_simple_crx/src/actions/index.js
Normal 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,
|
||||||
|
};;
|
||||||
|
|
||||||
@@ -1,35 +1,43 @@
|
|||||||
|
import { amazon_actions, getAllActionsMeta, getActionByName } from '../actions/index.js';
|
||||||
|
|
||||||
import {
|
// ──────────── Action 注册 ────────────
|
||||||
amazon_search_list,
|
|
||||||
amazon_set_language,
|
|
||||||
amazon_product_detail,
|
|
||||||
amazon_product_reviews,
|
|
||||||
amazon_product_detail_reviews,
|
|
||||||
} from '../actions/amazon.js';
|
|
||||||
|
|
||||||
// action 注册表:供 UI 下拉选择 + server bridge 调用
|
let action_list = [];
|
||||||
const actions = {
|
try {
|
||||||
amazon_search_list,
|
if (Array.isArray(amazon_actions)) {
|
||||||
amazon_set_language,
|
action_list = amazon_actions.filter(item => item && typeof item === 'object' && item.name);
|
||||||
amazon_product_detail,
|
console.log(`Loaded ${action_list.length} actions:`, action_list.map(item => item.name));
|
||||||
amazon_product_reviews,
|
} else {
|
||||||
amazon_product_detail_reviews,
|
console.warn('amazon_actions is not an array:', amazon_actions);
|
||||||
};
|
}
|
||||||
|
} catch (error) {
|
||||||
function list_actions_meta() {
|
console.error('Failed to load amazon_actions:', error);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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) => {
|
const fn = (payload) => {
|
||||||
emit_ui_event('push', { type: 'reply', ...payload, sender });
|
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 });
|
emit_ui_event('push', { type: 'log', action: 'log', data: payload, sender });
|
||||||
};
|
};
|
||||||
return fn;
|
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.browserAction.onClicked.addListener(() => {
|
||||||
chrome.tabs.create({ url: ui_page_url, active: true });
|
chrome.tabs.create({ url: ui_page_url, active: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||||
if (!message) {
|
// 忽略:空消息、UI 自身事件、page world 桥接
|
||||||
return;
|
if (!message || message.channel === 'ui_event' || message.channel === 'page_exec_bridge') return;
|
||||||
}
|
|
||||||
|
|
||||||
// UI 自己发出来的事件,background 不处理
|
// content -> background 推送
|
||||||
if (message.channel === 'ui_event') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// content -> background 的推送消息(通用)
|
|
||||||
if (message.type === 'push') {
|
if (message.type === 'push') {
|
||||||
emit_ui_event('push', {
|
console.log('Processing push message:', message.action);
|
||||||
type: 'push',
|
emit_ui_event('push', { type: 'push', action: message.action, data: message.data, sender });
|
||||||
action: message.action,
|
|
||||||
data: message.data,
|
|
||||||
sender,
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// UI -> background 的 action 调用
|
// 缺少 action
|
||||||
if (!message.action) {
|
if (!message.action) {
|
||||||
|
console.error('Missing action in message');
|
||||||
sendResponse && sendResponse({ ok: false, error: '缺少 action' });
|
sendResponse && sendResponse({ ok: false, error: '缺少 action' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// UI 获取 action 元信息(用于下拉/默认参数)
|
// 内置 action(同步处理,不需要 return true)
|
||||||
if (message.action === 'meta_actions') {
|
if (builtin_handlers[message.action]) {
|
||||||
sendResponse({ ok: true, data: list_actions_meta() });
|
builtin_handlers[message.action](message, sender, sendResponse);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// UI 刷新后台(重启 background page)
|
// 业务 action
|
||||||
if (message.action === 'reload_background') {
|
const action_item = getActionByName(message.action);
|
||||||
sendResponse({ ok: true });
|
if (!action_item || typeof action_item.handler !== 'function') {
|
||||||
setTimeout(() => {
|
console.error('Unknown action:', message.action);
|
||||||
location.reload();
|
|
||||||
}, 50);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fn = actions[message.action];
|
|
||||||
if (!fn) {
|
|
||||||
sendResponse({ ok: false, error: '未知 action: ' + message.action });
|
sendResponse({ ok: false, error: '未知 action: ' + message.action });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const request_id = `${Date.now()}_${Math.random().toString().slice(2)}`;
|
execute_action(action_item.handler, message, sender, sendResponse);
|
||||||
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 });
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,31 +2,37 @@
|
|||||||
* 服务端 Puppeteer 通过此页与 background 通讯(等同 UI 发 chrome.runtime.sendMessage)
|
* 服务端 Puppeteer 通过此页与 background 通讯(等同 UI 发 chrome.runtime.sendMessage)
|
||||||
* 页面内若需 Web Worker 做重计算,可在此 postMessage;当前直连 background 即可满足指令/结果
|
* 页面内若需 Web Worker 做重计算,可在此 postMessage;当前直连 background 即可满足指令/结果
|
||||||
*/
|
*/
|
||||||
(function () {
|
(() => {
|
||||||
function server_bridge_invoke(action, data) {
|
const server_bridge_invoke = (action, data) => {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise((resolve, reject) => {
|
||||||
if (!action) {
|
if (!action) {
|
||||||
reject(new Error('缺少 action'));
|
reject(new Error('缺少 action'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
chrome.runtime.sendMessage({ action: action, data: data || {} }, function (res) {
|
|
||||||
var err = chrome.runtime.lastError;
|
chrome.runtime.sendMessage(
|
||||||
|
{ action, data: data || {} },
|
||||||
|
(res) => {
|
||||||
|
const err = chrome.runtime.lastError;
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(new Error(err.message));
|
reject(new Error(err.message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!res) {
|
if (!res) {
|
||||||
reject(new Error('background 无响应'));
|
reject(new Error('background 无响应'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
resolve(res.data);
|
resolve(res.data);
|
||||||
} else {
|
} else {
|
||||||
reject(new Error(res.error || 'action 失败'));
|
reject(new Error(res.error || 'action 失败'));
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
window.server_bridge_invoke = server_bridge_invoke;
|
window.server_bridge_invoke = server_bridge_invoke;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -2,6 +2,29 @@
|
|||||||
// 目标:页面里触发 XHR/fetch 时派发 __REQUEST_DONE
|
// 目标:页面里触发 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) {
|
function inject_inline(fn) {
|
||||||
const el = document.createElement('script');
|
const el = document.createElement('script');
|
||||||
el.type = 'text/javascript';
|
el.type = 'text/javascript';
|
||||||
@@ -161,5 +184,8 @@
|
|||||||
F.__RequestWatcher = true;
|
F.__RequestWatcher = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 页面上下文通用方法:window.__mv2_simple_injected
|
||||||
|
inject_page_file_once('injected/injected.js', 'core_utils');
|
||||||
|
|
||||||
inject_inline(request_watcher);
|
inject_inline(request_watcher);
|
||||||
})();
|
})();
|
||||||
|
|||||||
53
mv2_simple_crx/src/examples/usage_example.js
Normal file
53
mv2_simple_crx/src/examples/usage_example.js
Normal 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
|
||||||
|
}
|
||||||
|
};
|
||||||
148
mv2_simple_crx/src/injected/injected.js
Normal file
148
mv2_simple_crx/src/injected/injected.js
Normal 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,
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
13
mv2_simple_crx/src/libs/action_meta.js
Normal file
13
mv2_simple_crx/src/libs/action_meta.js
Normal 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;
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ const RESPONSE_CODE_OK = 0;
|
|||||||
const RESPONSE_CODE_BAD_REQUEST = 10;
|
const RESPONSE_CODE_BAD_REQUEST = 10;
|
||||||
const RESPONSE_CODE_RUNTIME_ERROR = 30;
|
const RESPONSE_CODE_RUNTIME_ERROR = 30;
|
||||||
|
|
||||||
|
// 成功响应工厂:统一返回结构与成功码。
|
||||||
export function ok_response(data) {
|
export function ok_response(data) {
|
||||||
return {
|
return {
|
||||||
code: RESPONSE_CODE_OK,
|
code: RESPONSE_CODE_OK,
|
||||||
@@ -11,6 +12,7 @@ export function ok_response(data) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 失败响应工厂:统一错误码、错误消息和可选上下文。
|
||||||
export function fail_response(message, options) {
|
export function fail_response(message, options) {
|
||||||
const opts = options && typeof options === 'object' ? options : {};
|
const opts = options && typeof options === 'object' ? options : {};
|
||||||
const code = Number.isFinite(opts.code) ? Number(opts.code) : RESPONSE_CODE_RUNTIME_ERROR;
|
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 = {
|
export const response_code = {
|
||||||
ok: RESPONSE_CODE_OK,
|
ok: RESPONSE_CODE_OK,
|
||||||
bad_request: RESPONSE_CODE_BAD_REQUEST,
|
bad_request: RESPONSE_CODE_BAD_REQUEST,
|
||||||
runtime_error: RESPONSE_CODE_RUNTIME_ERROR,
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
61
mv2_simple_crx/src/libs/index.js
Normal file
61
mv2_simple_crx/src/libs/index.js
Normal 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;
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
// executeScript:MV2 使用 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);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,251 @@
|
|||||||
// openTab:MV2 版本(极简 + 回调风格)
|
// tabs.js:MV2 Tab 操作工具(Promise 风格)
|
||||||
|
|
||||||
import { execute_script } from './inject.js';
|
// ──────────── Chrome API Promise 封装 ────────────
|
||||||
|
|
||||||
function update_tab(tab_id, update_props) {
|
function chrome_tabs_get(tab_id) {
|
||||||
return new Promise((resolve_update, reject_update) => {
|
return new Promise((resolve, reject) => {
|
||||||
chrome.tabs.update(tab_id, update_props, (updated_tab) => {
|
chrome.tabs.get(tab_id, (t) => {
|
||||||
if (chrome.runtime.lastError) {
|
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
|
||||||
return reject_update(new Error(chrome.runtime.lastError.message));
|
resolve(t);
|
||||||
}
|
|
||||||
resolve_update(updated_tab || true);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
if (!tab) return tab;
|
||||||
|
|
||||||
tab.remove = function remove(delay_ms) {
|
tab.remove = function remove(delay_ms) {
|
||||||
@@ -24,84 +256,45 @@ function attach_tab_helpers(tab) {
|
|||||||
}, Math.max(0, delay_ms));
|
}, Math.max(0, delay_ms));
|
||||||
};
|
};
|
||||||
|
|
||||||
tab.execute_script = async function execute_script_on_tab(fn, args, run_at) {
|
tab.execute_script = (fn, args, run_at) => execute_script(tab.id, fn, args, run_at);
|
||||||
return await 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) {
|
tab.wait_complete = async function wait_complete(timeout_ms) {
|
||||||
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) {
|
|
||||||
const timeout = Number.isFinite(timeout_ms) ? Math.max(0, timeout_ms) : 45000;
|
const timeout = Number.isFinite(timeout_ms) ? Math.max(0, timeout_ms) : 45000;
|
||||||
return new Promise((resolve_wait, reject_wait) => {
|
const t0 = await chrome_tabs_get(tab.id).catch(() => null);
|
||||||
chrome.tabs.get(tab.id, (tab0) => {
|
if (t0 && t0.status === 'complete') return t0;
|
||||||
if (!chrome.runtime.lastError && tab0 && tab0.status === 'complete') {
|
return await wait_tab_status_complete(tab.id, timeout);
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 你期望的风格:tab.on_update_complete(() => tab.execute_script(...))
|
|
||||||
* - 每次页面刷新/导航完成(status=complete) 都会触发回调
|
|
||||||
* - 回调里可直接使用 tab.execute_script(而不是外部注入器封装)
|
|
||||||
*/
|
|
||||||
tab._on_update_complete_listener = null;
|
tab._on_update_complete_listener = null;
|
||||||
|
|
||||||
tab.on_update_complete = function on_update_complete(fn, options) {
|
tab.on_update_complete = function on_update_complete(fn, options) {
|
||||||
if (typeof fn !== 'function') return false;
|
if (typeof fn !== 'function' || !tab.id) return false;
|
||||||
if (!tab.id) return false;
|
|
||||||
tab.off_update_complete && tab.off_update_complete();
|
tab.off_update_complete && tab.off_update_complete();
|
||||||
|
|
||||||
let running = false;
|
let running = false;
|
||||||
const once = !!(options && options.once === true);
|
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) => {
|
const listener = async (updated_tab_id, change_info, updated_tab) => {
|
||||||
if (updated_tab_id !== tab.id) return;
|
if (updated_tab_id !== tab.id || !change_info || change_info.status !== 'complete') return;
|
||||||
if (!change_info || change_info.status !== 'complete') return;
|
|
||||||
if (running) return;
|
if (running) return;
|
||||||
running = true;
|
running = true;
|
||||||
const tab_obj = attach_tab_helpers(updated_tab || tab);
|
const tab_obj = attach_tab_helpers(updated_tab || tab);
|
||||||
try {
|
|
||||||
await fn(tab_obj, change_info);
|
await fn(tab_obj, change_info);
|
||||||
if (once) {
|
if (once) tab.off_update_complete && tab.off_update_complete();
|
||||||
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;
|
running = false;
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
chrome.tabs.onUpdated.addListener(listener);
|
chrome.tabs.onUpdated.addListener(listener);
|
||||||
tab._on_update_complete_listener = listener;
|
tab._on_update_complete_listener = listener;
|
||||||
|
|
||||||
// 注册时如果已 complete,立即触发一次,保证首屏也能执行注入
|
// 注册时如果已 complete,立即触发一次
|
||||||
chrome.tabs.get(tab.id, (t0) => {
|
chrome.tabs.get(tab.id, (t0) => {
|
||||||
if (chrome.runtime.lastError) return;
|
if (chrome.runtime.lastError) return;
|
||||||
if (t0 && t0.status === 'complete') {
|
if (t0 && t0.status === 'complete') {
|
||||||
@@ -111,11 +304,21 @@ function attach_tab_helpers(tab) {
|
|||||||
return true;
|
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() {
|
tab.off_update_complete = function off_update_complete() {
|
||||||
if (!tab._on_update_complete_listener) return;
|
if (!tab._on_update_complete_listener) return;
|
||||||
try {
|
try { chrome.tabs.onUpdated.removeListener(tab._on_update_complete_listener); } catch (_) {}
|
||||||
chrome.tabs.onUpdated.removeListener(tab._on_update_complete_listener);
|
|
||||||
} catch (_) { }
|
|
||||||
tab._on_update_complete_listener = null;
|
tab._on_update_complete_listener = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -130,55 +333,33 @@ function attach_tab_helpers(tab) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return tab;
|
return tab;
|
||||||
}
|
};
|
||||||
|
|
||||||
export function open_tab(url, options) {
|
// ──────────── 打开标签页 ────────────
|
||||||
// 保留原本 Promise 版本(内部复用)
|
|
||||||
options = options && typeof options === 'object' ? options : {};
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
export async function open_tab(url, options = {}) {
|
||||||
chrome.tabs.create(
|
const opts = { active: true, timeout: 45000, loadInBackground: false, ...options };
|
||||||
{
|
const tab = await chrome_tabs_create({
|
||||||
url: 'about:blank',
|
url: 'about:blank',
|
||||||
active: options.active !== false,
|
active: !opts.loadInBackground && opts.active,
|
||||||
},
|
|
||||||
(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);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
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(() => {
|
export async function close_tab(tab_id, delay_ms = 0) {
|
||||||
chrome.tabs.remove(tab_id, () => void 0);
|
if (delay_ms > 0) {
|
||||||
}, Math.max(0, delay_ms));
|
await new Promise((r) => setTimeout(r, delay_ms));
|
||||||
|
}
|
||||||
|
return await chrome_tabs_remove(tab_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// openTab 任务对象:用对象绑定方法,减少重复参数
|
// ──────────── Tab 任务对象 ────────────
|
||||||
|
|
||||||
export function create_tab_task(url) {
|
export function create_tab_task(url) {
|
||||||
const task = {
|
const task = {
|
||||||
url,
|
url,
|
||||||
@@ -189,34 +370,23 @@ export function create_tab_task(url) {
|
|||||||
height: 900,
|
height: 900,
|
||||||
target: null,
|
target: null,
|
||||||
active: true,
|
active: true,
|
||||||
// 你期望的写法:tab_task.on_updated = () => {}
|
|
||||||
on_error: null,
|
on_error: null,
|
||||||
on_updated: null,
|
on_updated: null,
|
||||||
|
|
||||||
set_bounds(bounds) {
|
set_bounds(bounds) {
|
||||||
bounds = bounds && typeof bounds === 'object' ? bounds : {};
|
bounds = bounds && typeof bounds === 'object' ? bounds : {};
|
||||||
if (Object.prototype.hasOwnProperty.call(bounds, 'top')) this.top = bounds.top;
|
if ('top' in bounds) this.top = bounds.top;
|
||||||
if (Object.prototype.hasOwnProperty.call(bounds, 'left')) this.left = bounds.left;
|
if ('left' in bounds) this.left = bounds.left;
|
||||||
if (Object.prototype.hasOwnProperty.call(bounds, 'width')) this.width = bounds.width;
|
if ('width' in bounds) this.width = bounds.width;
|
||||||
if (Object.prototype.hasOwnProperty.call(bounds, 'height')) this.height = bounds.height;
|
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;
|
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() {
|
async open_async() {
|
||||||
// 用 chrome.windows.create 新开窗口承载 tab
|
const win = await chrome_windows_create({
|
||||||
const win = await new Promise((resolve, reject) => {
|
|
||||||
chrome.windows.create(
|
|
||||||
{
|
|
||||||
url: 'about:blank',
|
url: 'about:blank',
|
||||||
type: 'popup',
|
type: 'popup',
|
||||||
focused: true,
|
focused: true,
|
||||||
@@ -224,34 +394,14 @@ export function create_tab_task(url) {
|
|||||||
left: this.left,
|
left: this.left,
|
||||||
width: this.width,
|
width: this.width,
|
||||||
height: this.height,
|
height: this.height,
|
||||||
},
|
|
||||||
(w) => {
|
|
||||||
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
|
|
||||||
resolve(w);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const tab0 = win && win.tabs && win.tabs[0] ? win.tabs[0] : null;
|
const tab0 = win && win.tabs && win.tabs[0] ? win.tabs[0] : null;
|
||||||
if (!tab0 || !tab0.id) {
|
if (!tab0 || !tab0.id) throw new Error('popup window 创建失败');
|
||||||
throw new Error('popup window 创建失败');
|
|
||||||
}
|
|
||||||
|
|
||||||
await update_tab(tab0.id, { url: this.url, active: this.active !== false });
|
await chrome_tabs_update(tab0.id, { url: this.url, active: this.active !== false });
|
||||||
|
const done_tab = await wait_tab_status_complete(tab0.id);
|
||||||
const tab_done = await new Promise((resolve) => {
|
return attach_tab_helpers(done_tab);
|
||||||
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);
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"description": "MV2 极简骨架:openTab + executeScript + __REQUEST_DONE 监听",
|
"description": "MV2 极简骨架:openTab + executeScript + __REQUEST_DONE 监听",
|
||||||
"permissions": [
|
"permissions": [
|
||||||
"tabs",
|
"tabs",
|
||||||
|
"storage",
|
||||||
"<all_urls>"
|
"<all_urls>"
|
||||||
],
|
],
|
||||||
"background": {
|
"background": {
|
||||||
@@ -20,7 +21,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"web_accessible_resources": [
|
"web_accessible_resources": [
|
||||||
"content/request_watcher.js"
|
"content/request_watcher.js",
|
||||||
|
"injected/injected.js"
|
||||||
],
|
],
|
||||||
"browser_action": {
|
"browser_action": {
|
||||||
"default_title": "mv2_simple_crx"
|
"default_title": "mv2_simple_crx"
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
const out = document.getElementById('out');
|
const out = document.getElementById('out');
|
||||||
const btn = document.getElementById('btn');
|
const btn = document.getElementById('btn');
|
||||||
|
|
||||||
function set_out(obj) {
|
const set_out = (obj) => {
|
||||||
out.textContent = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2);
|
out.textContent = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2);
|
||||||
}
|
};
|
||||||
|
|
||||||
btn.addEventListener('click', () => {
|
btn.addEventListener('click', () => {
|
||||||
set_out('执行中...');
|
set_out('执行中...');
|
||||||
|
|||||||
@@ -83,6 +83,22 @@ body {
|
|||||||
font-size: 12px;
|
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,
|
.input,
|
||||||
.textarea {
|
.textarea {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -159,6 +175,15 @@ body {
|
|||||||
overflow: auto;
|
overflow: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 响应区:不显示滚动条,长行自动换行(含无空格长串) */
|
||||||
|
.pre_response {
|
||||||
|
overflow: visible;
|
||||||
|
overflow-x: hidden;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
.pre_scroll {
|
.pre_scroll {
|
||||||
max-height: 520px;
|
max-height: 520px;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
|
|||||||
@@ -20,6 +20,10 @@
|
|||||||
<div class="card_title">调用</div>
|
<div class="card_title">调用</div>
|
||||||
|
|
||||||
<div class="form">
|
<div class="form">
|
||||||
|
<div>
|
||||||
|
<button id="btn_bg_reload" class="btn">刷新后台</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<label class="label">方法名(action)</label>
|
<label class="label">方法名(action)</label>
|
||||||
<!-- action 列表:由 background 注册;这里仅提供快速手动调用入口 -->
|
<!-- action 列表:由 background 注册;这里仅提供快速手动调用入口 -->
|
||||||
<select id="action_name" class="input">
|
<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>
|
<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>
|
<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">
|
<div class="row">
|
||||||
<button id="btn_run" class="btn primary">执行</button>
|
<button id="btn_run" class="btn primary">执行</button>
|
||||||
<button id="btn_clear" class="btn">清空日志</button>
|
<button id="btn_clear" class="btn">清空日志</button>
|
||||||
<button id="btn_bg_reload" class="btn">刷新后台</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="hint">
|
<div class="hint">
|
||||||
@@ -54,7 +60,7 @@
|
|||||||
<label class="label">动作日志</label>
|
<label class="label">动作日志</label>
|
||||||
<pre id="action_log" class="pre pre_small"></pre>
|
<pre id="action_log" class="pre pre_small"></pre>
|
||||||
<div class="card_title">响应</div>
|
<div class="card_title">响应</div>
|
||||||
<pre id="last_response" class="pre"></pre>
|
<pre id="last_response" class="pre pre_response"></pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,24 +6,25 @@ const btn_clear_el = document.getElementById('btn_clear');
|
|||||||
const btn_bg_reload_el = document.getElementById('btn_bg_reload');
|
const btn_bg_reload_el = document.getElementById('btn_bg_reload');
|
||||||
const last_response_el = document.getElementById('last_response');
|
const last_response_el = document.getElementById('last_response');
|
||||||
const action_log_el = document.getElementById('action_log');
|
const action_log_el = document.getElementById('action_log');
|
||||||
|
const opt_keep_tab_open_el = document.getElementById('opt_keep_tab_open');
|
||||||
let actions_meta = {};
|
let actions_meta = {};
|
||||||
const ui_state = { last_result: null, actions: [] };
|
const ui_state = { last_result: null, actions: [] };
|
||||||
|
|
||||||
function now_time() {
|
const now_time = () => {
|
||||||
const d = new Date();
|
const d = new Date();
|
||||||
const pad = (n) => String(n).padStart(2, '0');
|
const pad = (n) => String(n).padStart(2, '0');
|
||||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||||
}
|
};
|
||||||
|
|
||||||
function safe_json_parse(text) {
|
const safe_json_parse = (text) => {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(text);
|
return JSON.parse(text);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return { __parse_error: e.message, __raw: text };
|
return { __parse_error: e.message, __raw: text };
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
function pick_main_result(res) {
|
const pick_main_result = (res) => {
|
||||||
// 右侧只展示最核心的数据,避免被 ok/request_id 包裹层干扰
|
// 右侧只展示最核心的数据,避免被 ok/request_id 包裹层干扰
|
||||||
if (res && res.ok && res.data) {
|
if (res && res.ok && res.data) {
|
||||||
// 约定:action 返回的核心结果放在 data.result(例如 amazon_search_list 的 stage=list)
|
// 约定:action 返回的核心结果放在 data.result(例如 amazon_search_list 的 stage=list)
|
||||||
@@ -31,14 +32,14 @@ function pick_main_result(res) {
|
|||||||
return res.data;
|
return res.data;
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
};
|
||||||
|
|
||||||
function render_state() {
|
const render_state = () => {
|
||||||
last_response_el.textContent = JSON.stringify(ui_state.last_result, null, 2);
|
last_response_el.textContent = JSON.stringify(ui_state.last_result, null, 2);
|
||||||
action_log_el.textContent = ui_state.actions.join('\n');
|
action_log_el.textContent = ui_state.actions.join('\n');
|
||||||
}
|
};
|
||||||
|
|
||||||
function push_action(obj) {
|
const push_action = (obj) => {
|
||||||
// 动作日志只保留单行文本,避免 JSON 换行太长
|
// 动作日志只保留单行文本,避免 JSON 换行太长
|
||||||
const ts = now_time();
|
const ts = now_time();
|
||||||
const type = obj && obj.type ? String(obj.type) : 'action';
|
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);
|
ui_state.actions.splice(0, ui_state.actions.length - 200);
|
||||||
}
|
}
|
||||||
render_state();
|
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', () => {
|
btn_run_el.addEventListener('click', () => {
|
||||||
const action = action_name_el.value;
|
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 });
|
push_action({ type: 'call', action, params });
|
||||||
ui_state.last_result = { running: true, action, params };
|
ui_state.last_result = { running: true, action, params };
|
||||||
|
|||||||
@@ -25,4 +25,4 @@ await start_all_cron_tasks();
|
|||||||
|
|
||||||
app.listen(port);
|
app.listen(port);
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log(`server listening on ${port}`);
|
console.log(`[${new Date().toLocaleString()}] server listening on ${port}`);
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ export function get_sequelize_options() {
|
|||||||
? (sql, timing_ms) => {
|
? (sql, timing_ms) => {
|
||||||
if (cfg.crawler.log_sql_benchmark === true && typeof timing_ms === 'number') {
|
if (cfg.crawler.log_sql_benchmark === true && typeof timing_ms === 'number') {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log('[sql]', { timing_ms, sql });
|
console.log(`[${new Date().toLocaleString()}] [sql]`, { timing_ms, sql });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log('[sql]', sql);
|
console.log(`[${new Date().toLocaleString()}] [sql]`, sql);
|
||||||
}
|
}
|
||||||
: false,
|
: false,
|
||||||
define: {
|
define: {
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ import { sequelize } from '../models/index.js';
|
|||||||
|
|
||||||
await sequelize.sync({ alter: true });
|
await sequelize.sync({ alter: true });
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log('sync ok');
|
console.log(`[${new Date().toLocaleString()}] sync ok`);
|
||||||
await sequelize.close();
|
await sequelize.close();
|
||||||
|
|||||||
@@ -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 };
|
const list_payload = { category_keyword, limit };
|
||||||
if (sort_by) {
|
if (sort_by) {
|
||||||
list_payload.sort_by = sort_by;
|
list_payload.sort_by = sort_by;
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ export async function invoke_extension_action(action_name, action_payload, optio
|
|||||||
const log_enabled = cfg.crawler.log_invoke_action;
|
const log_enabled = cfg.crawler.log_invoke_action;
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log('[invoke_extension_action] start', {
|
console.log(`[${new Date().toLocaleString()}] [invoke_extension_action] start`, {
|
||||||
action_name,
|
action_name,
|
||||||
has_payload: !!action_payload,
|
has_payload: !!action_payload,
|
||||||
keys: action_payload && typeof action_payload === 'object' ? Object.keys(action_payload).slice(0, 20) : []
|
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) {
|
if (log_enabled) {
|
||||||
// eslint-disable-next-line no-console
|
// 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;
|
return action_res;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log('[invoke_extension_action] fail', {
|
console.log(`[${new Date().toLocaleString()}] [invoke_extension_action] fail`, {
|
||||||
action_name,
|
action_name,
|
||||||
cost_ms: Date.now() - started_at,
|
cost_ms: Date.now() - started_at,
|
||||||
error: (err && err.message) || String(err)
|
error: (err && err.message) || String(err)
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ async function run_cron_task(task) {
|
|||||||
async function run_cron_task_with_guard(task_name, task) {
|
async function run_cron_task_with_guard(task_name, task) {
|
||||||
if (running_task_name_set.has(task_name)) {
|
if (running_task_name_set.has(task_name)) {
|
||||||
// eslint-disable-next-line no-console
|
// 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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,7 +51,8 @@ async function run_cron_task_with_guard(task_name, task) {
|
|||||||
try {
|
try {
|
||||||
await run_cron_task(task);
|
await run_cron_task(task);
|
||||||
} catch (error) {
|
} 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 {
|
} finally {
|
||||||
running_task_name_set.delete(task_name);
|
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 () => {
|
const job = cron.schedule(task.cron_expression, async () => {
|
||||||
await run_cron_task_with_guard(task_name, task);
|
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);
|
cron_jobs.push(job);
|
||||||
|
|
||||||
if (run_now) {
|
if (run_now) {
|
||||||
// 启动时额外立刻跑一次(仍走 guard,避免与 cron 触发撞车)
|
// 启动时额外立刻跑一次(仍走 guard,避免与 cron 触发撞车)
|
||||||
// eslint-disable-next-line no-console
|
// 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);
|
await run_cron_task_with_guard(task_name, task);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user