Phụ lục API script
Mục tiêu
Mô tả các khả năng window.api mà script trang và script chặn API có thể sử dụng, bao gồm đọc cấu hình, request HTTP, dữ liệu người dùng, công cụ DOM, tiện ích chung và đọc header request/response.
Script trang và script chặn API thông thường có thể dùng window.api. Script SSE chỉ đảm bảo truyền vào data và thường không phụ thuộc vào window.api.
interface Window {
api: {
user: UserApi;
http: HttpApi;
config: Record<string, unknown>;
dom: DomApi;
utils: UtilsApi;
header(headerName: string, isRequestHeader: boolean): Promise<string | string[] | undefined>;
};
}api.config
Đọc cấu hình tùy chỉnh trong môi trường script của trang.
config: Record<string, unknown>Ví dụ:
const apiBase = api.config.apiBase;api.http
api.http cung cấp helper HTTP cho script người dùng. api.http.ajax chạy request thực tế trong main process của trình duyệt, nên không bị giới hạn bởi chính sách CORS của trang.
api.http.ajax(options)
Gửi request HTTP.
ajax(options: {
url: string;
method?: string;
data?: any;
headers?: Record<string, string>;
timeout?: number;
dataType?: 'json' | 'text' | 'html' | 'arrayBuffer';
contentType?: string;
processData?: boolean;
}): Promise<{
ok: boolean;
status: number;
statusText: string;
data?: any;
error?: string;
timeout?: boolean;
}>| Tùy chọn | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
url | string | - | URL request. |
method | string | GET | HTTP method. |
data | any | - | Dữ liệu request. Với GET và HEAD, dữ liệu được serialize vào query string. Với method khác, dữ liệu được ghi vào request body. |
headers | Record<string, string> | {} | Request header. |
timeout | number | - | Timeout tính bằng mili giây. Chỉ có hiệu lực khi lớn hơn 0. |
dataType | 'json' | 'text' | 'html' | 'arrayBuffer' | json | Cách parse response. |
contentType | string | application/x-www-form-urlencoded; charset=UTF-8 | Content-Type của request body. |
processData | boolean | true | Có tự động serialize data hay không. Đặt false để truyền trực tiếp data làm request body. |
Giá trị trả về:
| Trường | Kiểu | Mô tả |
|---|---|---|
ok | boolean | true với response HTTP 2xx; false khi lỗi parse, lỗi HTTP, timeout, abort hoặc lỗi mạng. |
status | number | HTTP status code. 0 biểu thị timeout, abort hoặc lỗi tầng mạng. |
statusText | string | HTTP status text, hoặc timeout, abort, error với lỗi không phải HTTP. |
data | any | Dữ liệu response đã parse, có khi parse thành công. |
error | string | Thông báo lỗi, có khi lỗi parse hoặc lỗi không phải HTTP. |
timeout | boolean | true khi request bị hủy bởi timeout đã cấu hình. |
Ví dụ:
const ret = await api.http.ajax({
url: 'https://example.com/api/profile',
method: 'GET',
dataType: 'json',
timeout: 10000
});
if (ret.ok) {
console.log(ret.data);
}const ret = await api.http.ajax({
url: 'https://example.com/api/items',
method: 'POST',
contentType: 'application/json',
data: { name: 'demo' }
});api.user
api.user dùng để đọc và ghi dữ liệu liên quan đến người dùng trong quá trình script chạy.
Tham số chung:
| Tham số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
site | boolean | false | Có lưu tách theo trang hay không. |
account | boolean | false | Có lưu tách theo tài khoản hay không. |
did | boolean | false | Có lưu tách theo thiết bị hay không. |
api.user.put(name, value, site, account, did)
Lưu cặp khóa-giá trị chỉ định.
put(
name: string,
value: string,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<{ status: boolean }>Ví dụ:
await api.user.put('token', 'abc123');api.user.get(name, site, account, did)
Đọc cặp khóa-giá trị chỉ định.
get(
name: string,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<{ value: string | null, status: boolean }>Ví dụ:
const ret = await api.user.get('token');
console.log(ret.value);api.user.remove(name, site, account, did)
Xóa cặp khóa-giá trị chỉ định.
remove(
name: string,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<{ status: boolean }>Ví dụ:
await api.user.remove('token');api.user.incr(name, step, site, account, did)
Tăng giá trị số của khóa chỉ định theo bước. Khi khóa không tồn tại, hệ thống tạo khóa với giá trị step.
incr(
name: string,
step?: number,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<{ status: boolean, value: number | string }>Ví dụ:
const ret = await api.user.incr('count', 1);
console.log(ret.value);api.user.decr(name, step, site, account, did)
Giảm giá trị số của khóa chỉ định theo bước. Khi khóa không tồn tại, hệ thống tạo khóa với giá trị step * -1.
decr(
name: string,
step?: number,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<{ status: boolean, value: number | string }>Ví dụ:
const ret = await api.user.decr('count', 1);
console.log(ret.value);api.user.startsWith(prefix, site, account, did)
Tìm tất cả dữ liệu có tên khóa bắt đầu bằng tiền tố chỉ định.
startsWith(
prefix: string,
site?: boolean,
account?: boolean,
did?: boolean
): Promise<Array<{ name: string, value: string }>>Ví dụ:
const items = await api.user.startsWith('cache:');api.user.countAll(name, site, account)
Đếm số bản ghi của tên khóa chỉ định.
countAll(
name: string,
site?: boolean,
account?: boolean
): Promise<{ value: number, status: boolean }>Ví dụ:
const ret = await api.user.countAll('token');
console.log(ret.value);api.user.sumAll(name, site, account)
Tính tổng số của các giá trị tương ứng với tên khóa chỉ định.
sumAll(
name: string,
site?: boolean,
account?: boolean
): Promise<{ value: number, status: boolean }>Ví dụ:
const ret = await api.user.sumAll('score');
console.log(ret.value);api.dom
api.dom cung cấp truy vấn DOM, kiểm tra hiển thị, listener kết nối, listener kích thước và tạo overlay.
Hỗ trợ selector:
| Cách viết | Mô tả |
|---|---|
.button.primary | Selector CSS. |
xpath://div[@id="app"] | Selector XPath. |
.dialog:p | Trả về phần tử cha của phần tử khớp. |
.dialog:p2 | Trả về phần tử cha cách phần tử khớp hai cấp. |
.header:bottom | Trong phương thức biên overlay, dùng biên dưới của phần tử đích. |
.sidebar:right | Trong phương thức biên overlay, dùng biên phải của phần tử đích. |
api.dom.createMutationObserver(ele, bindStr, childList, subtree, attributes, characterData, fn)
Tạo và cache MutationObserver. Nếu ele[bindStr] đã tồn tại, observer hiện có được trả về trực tiếp.
createMutationObserver(
ele: Element,
bindStr: string,
childList: boolean,
subtree: boolean,
attributes: boolean,
characterData: boolean,
fn: (mutations: MutationRecord[]) => void
): MutationObserverVí dụ:
api.dom.createMutationObserver(
document.body,
'__bodyObserver__',
true,
true,
false,
false,
(mutations) => console.log(mutations)
);api.dom.querySelector(doc, cssOrXPathSelector)
Truy vấn phần tử khớp đầu tiên.
querySelector(doc: Document, cssOrXPathSelector: string): HTMLElement | nullVí dụ:
const el = api.dom.querySelector(document, 'xpath://button[contains(.,"Submit")]');api.dom.querySelectorAll(doc, cssOrXPathSelector)
Truy vấn tất cả phần tử khớp.
querySelectorAll(doc: Document, cssOrXPathSelector: string): HTMLElement[]Ví dụ:
const buttons = api.dom.querySelectorAll(document, 'button.primary');api.dom.isVisible(ele)
Xác định phần tử có nằm trong vùng giao hiển thị hay không.
isVisible(ele: HTMLElement): Promise<boolean>Ví dụ:
if (await api.dom.isVisible(el)) {
console.log('visible');
}api.dom.getVisibleRect(ele)
Lấy hình chữ nhật vùng hiển thị hiện tại của phần tử.
getVisibleRect(ele: HTMLElement): Promise<DOMRectReadOnly>Ví dụ:
const rect = await api.dom.getVisibleRect(el);
console.log(rect.left, rect.top, rect.width, rect.height);api.dom.getConnectListeners()
Lấy danh sách listener kết nối hiện tại.
getConnectListeners(): Array<{
querySelector: string;
callback: (isConnected: boolean) => void;
isConnected?: boolean;
}>Ví dụ:
api.dom.addConnectListener('.modal', () => {});
console.log(api.dom.getConnectListeners());api.dom.addConnectListener(cssOrXPathSelector, callback)
Theo dõi phần tử đích xuất hiện trong tài liệu hoặc biến mất khỏi tài liệu.
addConnectListener(
cssOrXPathSelector: string,
callback: (isConnected: boolean) => void
): voidVí dụ:
api.dom.addConnectListener('.dialog', (isConnected) => {
console.log('dialog:', isConnected);
});api.dom.removeConnectListener(cssOrXPathSelectors)
Gỡ listener kết nối tương ứng với các selector chỉ định.
removeConnectListener(cssOrXPathSelectors: string[]): voidVí dụ:
api.dom.removeConnectListener(['.dialog', '.toast']);api.dom.addResizeListener(cssOrXPathSelector, bindWindowStr, callback, createObserver, delayTime)
Theo dõi thay đổi kích thước và vị trí của phần tử đích. Khi phần tử không tồn tại, callback nhận new DOMRect(0, 0, 0, 0).
addResizeListener(
cssOrXPathSelector: string,
bindWindowStr: string,
callback: (rect: DOMRect) => void,
createObserver?: boolean,
delayTime?: number
): ResizeObserver | (() => void)Ví dụ:
api.dom.addResizeListener('.target', '__targetResize__', (rect) => {
console.log(rect.width, rect.height);
});api.dom.createOverlayBy(cssOrXPathSelector, bindWindowStr, createObserver, delayTime, fn)
Tạo overlay fixed-position đi theo vùng hiển thị của phần tử đích.
createOverlayBy(
cssOrXPathSelector: string,
bindWindowStr: string,
createObserver?: boolean,
delayTime?: number,
fn?: (rect: DOMRectReadOnly) => void
): HTMLElementVí dụ:
const overlay = api.dom.createOverlayBy('.target', '__overlay__');
overlay.style.border = '2px solid #f00';
overlay.style.pointerEvents = 'none';
overlay.style.zIndex = '999999';api.dom.createOverlayByBorder(bindWindowStr, top, right, bottom, left, createObserver, delayTime)
Tạo overlay fixed-position bằng bốn cạnh. Mỗi cạnh có thể là giá trị pixel dạng số hoặc selector; selector có thể dùng :top, :right, :bottom, :left.
createOverlayByBorder(
bindWindowStr: string,
top: string | number,
right: string | number,
bottom: string | number,
left: string | number,
createObserver?: boolean,
delayTime?: number
): HTMLElementVí dụ:
const panel = api.dom.createOverlayByBorder(
'__centerPanel__',
'header:bottom',
20,
'footer:top',
'.sidebar:right'
);
panel.style.background = 'rgba(0,0,0,.08)';api.utils
api.utils.wait(fn, timeoutMs, intervalMs)
Polling cho đến khi hàm điều kiện trả về giá trị đúng.
wait(
fn: () => boolean,
timeoutMs: number,
intervalMs?: number
): Promise<void>Sau khi timeout, sẽ ném Error("Timeout: function did not return true in time.").
Ví dụ:
await api.utils.wait(
() => !!api.dom.querySelector(document, '.ready'),
10000,
200
);api.utils.runScript(code, callback)
Thực thi mã JavaScript trên trang hiện tại.
runScript(
code: string,
callback?: (result: any, error: Error) => void
): Promise<any>Ví dụ:
const title = await api.utils.runScript('document.title');
console.log(title);api.header(headerName, isRequestHeader)
Đọc header request hoặc response do trình duyệt từ xa ghi nhận.
header(
headerName: string,
isRequestHeader: boolean
): Promise<string | string[] | undefined>| Tham số | Kiểu | Mô tả |
|---|---|---|
headerName | string | Tên header request hoặc response; khi đọc sẽ chuyển thành chữ thường. |
isRequestHeader | boolean | true đọc header request, false đọc header response. |
Lưu ý:
- Chỉ header đã thêm trong cấu hình trang mới được ghi nhận.
- Header request đến từ header mà trình duyệt từ xa gửi.
- Header response đến từ header mà trình duyệt từ xa nhận.
- Header response có thể trả về mảng chuỗi.
Ví dụ:
const cookie = await api.header('cookie', true);
const setCookie = await api.header('set-cookie', false);