mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 浏览器扩展完全支持热更新
This commit is contained in:
@@ -29,15 +29,16 @@ async function main() {
|
||||
{
|
||||
id: 'pdd-ad-fee',
|
||||
name: '拼多多商品推广费同步',
|
||||
version: '0.1.0',
|
||||
description: '从推广总览读取单日总花费并同步到 BI(壳内嵌入执行;远程包用于版本校验)',
|
||||
version: '0.2.0',
|
||||
description:
|
||||
'从推广总览读取单日总花费并同步到 BI(MAIN world 远程脚本,更新后端静态资源即可热更新)',
|
||||
matchUrlPatterns: [
|
||||
'*://yingxiao.pinduoduo.com/*',
|
||||
'https://yingxiao.pinduoduo.com/',
|
||||
],
|
||||
entry: entryFile,
|
||||
sha256,
|
||||
executionWorld: 'extension',
|
||||
executionWorld: 'main',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -7,10 +7,23 @@ export interface ApiResponseBody<T> {
|
||||
data: T;
|
||||
}
|
||||
|
||||
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
|
||||
|
||||
let openApiOverride: OpenApiRequestFn | null = null;
|
||||
|
||||
/** 功能包在 main world 安装桥接实现时调用 */
|
||||
export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
|
||||
openApiOverride = fn;
|
||||
}
|
||||
|
||||
export async function openApiRequest<T>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<T> {
|
||||
if (openApiOverride) {
|
||||
return openApiOverride<T>(path, init);
|
||||
}
|
||||
|
||||
const settings = await getSettings();
|
||||
if (!settings.apiBaseUrl) {
|
||||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
|
||||
|
||||
@@ -1,15 +1,103 @@
|
||||
/**
|
||||
* Background Service Worker:生命周期与消息转发占位。
|
||||
* 第一阶段业务请求由 Popup 直接发起;Content 由 Manifest 注入。
|
||||
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
|
||||
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
|
||||
*/
|
||||
|
||||
type InjectMessage = {
|
||||
type: 'INJECT_MAIN_SCRIPT';
|
||||
payload: { code: string };
|
||||
};
|
||||
|
||||
type CallMessage = {
|
||||
type: 'CALL_MAIN_FEATURE';
|
||||
payload: { featureId: string; action: 'mount' | 'unmount' };
|
||||
};
|
||||
|
||||
type BgMessage = InjectMessage | CallMessage | { type: 'BACKGROUND_PING' };
|
||||
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
console.info('[ecbi-extension] installed');
|
||||
});
|
||||
|
||||
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse) => {
|
||||
if (message?.type === 'BACKGROUND_PING') {
|
||||
sendResponse({ ok: true, data: { pong: true } });
|
||||
return true;
|
||||
}
|
||||
|
||||
const tabId = sender.tab?.id;
|
||||
if (tabId == null) {
|
||||
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message?.type === 'INJECT_MAIN_SCRIPT') {
|
||||
void chrome.scripting
|
||||
.executeScript({
|
||||
target: { tabId },
|
||||
world: 'MAIN',
|
||||
func: (source: string) => {
|
||||
// 扩展注入的 MAIN world 函数内执行,不受页面 CSP 限制
|
||||
const run = new Function(source);
|
||||
run();
|
||||
},
|
||||
args: [message.payload.code],
|
||||
})
|
||||
.then(() => sendResponse({ ok: true }))
|
||||
.catch((error: unknown) => {
|
||||
sendResponse({
|
||||
ok: false,
|
||||
message: error instanceof Error ? error.message : '注入脚本失败',
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (message?.type === 'CALL_MAIN_FEATURE') {
|
||||
const { featureId, action } = message.payload;
|
||||
void chrome.scripting
|
||||
.executeScript({
|
||||
target: { tabId },
|
||||
world: 'MAIN',
|
||||
func: async (id: string, act: 'mount' | 'unmount') => {
|
||||
const bag = (
|
||||
globalThis as typeof globalThis & {
|
||||
__ECBI_FEATURES__?: Record<
|
||||
string,
|
||||
{
|
||||
mount?: () => void | Promise<void>;
|
||||
unmount?: () => void | Promise<void>;
|
||||
}
|
||||
>;
|
||||
}
|
||||
).__ECBI_FEATURES__;
|
||||
const mod = bag?.[id];
|
||||
if (!mod) {
|
||||
throw new Error(`功能未注册:${id}`);
|
||||
}
|
||||
if (act === 'mount') {
|
||||
if (typeof mod.mount !== 'function') {
|
||||
throw new Error(`功能无 mount:${id}`);
|
||||
}
|
||||
await mod.mount();
|
||||
return;
|
||||
}
|
||||
if (typeof mod.unmount !== 'function') {
|
||||
throw new Error(`功能无 unmount:${id}`);
|
||||
}
|
||||
await mod.unmount();
|
||||
},
|
||||
args: [featureId, action],
|
||||
})
|
||||
.then(() => sendResponse({ ok: true }))
|
||||
.catch((error: unknown) => {
|
||||
sendResponse({
|
||||
ok: false,
|
||||
message: error instanceof Error ? error.message : '调用功能失败',
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { createApp, type App } from 'vue';
|
||||
|
||||
import { emitFeatureEvent } from '@/features/runtime/mainWorldAdapters';
|
||||
|
||||
import FloatingPanel from './FloatingPanel.vue';
|
||||
import styles from './styles.css?inline';
|
||||
|
||||
const HOST_ID = 'ecbi-float-host';
|
||||
const LAUNCHER_ID = 'ecbi-float-launcher';
|
||||
const FEATURE_ID = 'pdd-ad-fee';
|
||||
|
||||
let app: App<Element> | null = null;
|
||||
let visible = false;
|
||||
@@ -53,6 +56,7 @@ function showLauncher() {
|
||||
btn.addEventListener('click', () => {
|
||||
minimized = false;
|
||||
setFloatingVisible(true);
|
||||
emitFeatureEvent(FEATURE_ID, 'restored');
|
||||
});
|
||||
document.documentElement.appendChild(btn);
|
||||
}
|
||||
@@ -87,6 +91,7 @@ function mountApp() {
|
||||
unmountApp();
|
||||
showLauncher();
|
||||
visible = true;
|
||||
emitFeatureEvent(FEATURE_ID, 'minimized');
|
||||
},
|
||||
});
|
||||
app.mount(mountEl);
|
||||
@@ -98,10 +103,14 @@ export function isFloatingVisible(): boolean {
|
||||
|
||||
export function setFloatingVisible(next: boolean): boolean {
|
||||
if (!next) {
|
||||
const wasVisible = visible;
|
||||
visible = false;
|
||||
minimized = false;
|
||||
unmountApp();
|
||||
removeLauncher();
|
||||
if (wasVisible) {
|
||||
emitFeatureEvent(FEATURE_ID, 'closed');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -352,19 +352,19 @@ button.ecbi-heat-cell:disabled {
|
||||
}
|
||||
|
||||
.ecbi-heat-l1 {
|
||||
background: #bae0ff;
|
||||
background: #9be9a8;
|
||||
}
|
||||
|
||||
.ecbi-heat-l2 {
|
||||
background: #69b1ff;
|
||||
background: #40c463;
|
||||
}
|
||||
|
||||
.ecbi-heat-l3 {
|
||||
background: #1677ff;
|
||||
background: #30a14e;
|
||||
}
|
||||
|
||||
.ecbi-heat-l4 {
|
||||
background: #0958d9;
|
||||
background: #216e39;
|
||||
}
|
||||
|
||||
.ecbi-heat-out {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { resolveAdapter } from '@/platform/core/PlatformDetector';
|
||||
import {
|
||||
getActiveFeatureId,
|
||||
isFeatureUiVisible,
|
||||
mountFeature,
|
||||
unmountActiveFeature,
|
||||
} from '@/features/runtime/registry';
|
||||
import { startBridgeHost } from '@/features/runtime/bridgeHost';
|
||||
import { resolveAdapter } from '@/platform/core/PlatformDetector';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import {
|
||||
isExtensionMessage,
|
||||
@@ -12,11 +14,7 @@ import {
|
||||
} from '@/shared/messages';
|
||||
import type { AdvertisingCostBatch } from '@/types/advertisingCost';
|
||||
|
||||
import {
|
||||
isFloatingVisible,
|
||||
setFloatingVisible,
|
||||
toggleFloatingPanel,
|
||||
} from './floating/mount';
|
||||
startBridgeHost();
|
||||
|
||||
async function handleMessage(message: ExtensionMessage): Promise<ExtensionResponse> {
|
||||
const adapter = resolveAdapter(location.href);
|
||||
@@ -37,18 +35,32 @@ async function handleMessage(message: ExtensionMessage): Promise<ExtensionRespon
|
||||
return { ok: true, data };
|
||||
}
|
||||
case 'TOGGLE_FLOATING_PANEL': {
|
||||
const visible = toggleFloatingPanel();
|
||||
return { ok: true, data: { visible } };
|
||||
if (isFeatureUiVisible()) {
|
||||
await unmountActiveFeature();
|
||||
return { ok: true, data: { visible: false } };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
code: 'UNKNOWN',
|
||||
message: '请从 Popup 打开功能(需下载远程脚本)',
|
||||
};
|
||||
}
|
||||
case 'SET_FLOATING_PANEL': {
|
||||
const visible = setFloatingVisible(message.payload.visible);
|
||||
return { ok: true, data: { visible } };
|
||||
if (!message.payload.visible) {
|
||||
await unmountActiveFeature();
|
||||
return { ok: true, data: { visible: false } };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
code: 'UNKNOWN',
|
||||
message: '请从 Popup 打开功能(需下载远程脚本)',
|
||||
};
|
||||
}
|
||||
case 'GET_FLOATING_PANEL_STATE': {
|
||||
return { ok: true, data: { visible: isFloatingVisible() } };
|
||||
return { ok: true, data: { visible: isFeatureUiVisible() } };
|
||||
}
|
||||
case 'MOUNT_FEATURE': {
|
||||
await mountFeature(message.payload.featureId);
|
||||
await mountFeature(message.payload.featureId, message.payload.code);
|
||||
return { ok: true, data: { featureId: message.payload.featureId } };
|
||||
}
|
||||
case 'UNMOUNT_FEATURE': {
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { FeatureHandle, FeatureModule, FeatureMountContext } from '@/features/runtime/types';
|
||||
import {
|
||||
isFloatingVisible,
|
||||
setFloatingVisible,
|
||||
toggleFloatingPanel,
|
||||
} from '@/content/floating/mount';
|
||||
|
||||
/**
|
||||
* 嵌入式实现:与远程发布的 pdd-ad-fee 同 id。
|
||||
* 壳内直接 mount;远程 JS 用于版本对齐与后续 main-world 执行。
|
||||
*/
|
||||
export const pddAdFeeEmbeddedFeature: FeatureModule = {
|
||||
id: 'pdd-ad-fee',
|
||||
async mount(_ctx: FeatureMountContext): Promise<FeatureHandle> {
|
||||
setFloatingVisible(true);
|
||||
return {
|
||||
unmount: () => {
|
||||
setFloatingVisible(false);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export function isPddAdFeePanelVisible(): boolean {
|
||||
return isFloatingVisible();
|
||||
}
|
||||
|
||||
export function togglePddAdFeePanel(): boolean {
|
||||
return toggleFloatingPanel();
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
/**
|
||||
* 远程功能包入口(IIFE 构建)。
|
||||
* 当前阶段导出元数据;真正 UI 仍由壳内 embedded 模块挂载。
|
||||
* 后续可将 FloatingPanel 整包打入此入口并在 main world 执行。
|
||||
* 远程功能包入口(IIFE → dist-features/pdd-ad-fee.js)。
|
||||
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
|
||||
*/
|
||||
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
|
||||
import { setFloatingVisible } from '@/content/floating/mount';
|
||||
|
||||
const FEATURE_ID = 'pdd-ad-fee';
|
||||
const FEATURE_VERSION = '0.2.0';
|
||||
|
||||
export interface RemoteFeatureExport {
|
||||
id: string;
|
||||
version: string;
|
||||
executionWorld: 'extension';
|
||||
executionWorld: 'main';
|
||||
mount: () => Promise<void>;
|
||||
unmount: () => Promise<void>;
|
||||
}
|
||||
|
||||
const meta: RemoteFeatureExport = {
|
||||
installMainWorldAdapters();
|
||||
|
||||
const feature: RemoteFeatureExport = {
|
||||
id: FEATURE_ID,
|
||||
version: '0.1.0',
|
||||
executionWorld: 'extension',
|
||||
version: FEATURE_VERSION,
|
||||
executionWorld: 'main',
|
||||
async mount() {
|
||||
setFloatingVisible(true);
|
||||
},
|
||||
async unmount() {
|
||||
setFloatingVisible(false);
|
||||
},
|
||||
};
|
||||
|
||||
declare global {
|
||||
@@ -27,6 +40,6 @@ const g = globalThis as typeof globalThis & {
|
||||
__ECBI_FEATURES__?: Record<string, RemoteFeatureExport>;
|
||||
};
|
||||
g.__ECBI_FEATURES__ = g.__ECBI_FEATURES__ ?? {};
|
||||
g.__ECBI_FEATURES__[FEATURE_ID] = meta;
|
||||
g.__ECBI_FEATURES__[FEATURE_ID] = feature;
|
||||
|
||||
export default meta;
|
||||
export default feature;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Content Script(isolated)侧桥接主机:代发 Open API、读写 chrome.storage。
|
||||
*/
|
||||
import { openApiRequest } from '@/api/client';
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { getSettings, saveSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_SHELL_SOURCE,
|
||||
isBridgeFeatureEvent,
|
||||
isBridgeRpcRequest,
|
||||
type BridgeRpcRequest,
|
||||
type BridgeRpcResult,
|
||||
} from './bridgeProtocol';
|
||||
import { clearActiveIfFeature, notifyFeatureEvent } from './registry';
|
||||
|
||||
let started = false;
|
||||
|
||||
function reply(result: BridgeRpcResult): void {
|
||||
window.postMessage(result, '*');
|
||||
}
|
||||
|
||||
async function handleRpc(msg: BridgeRpcRequest): Promise<void> {
|
||||
try {
|
||||
let data: unknown;
|
||||
switch (msg.rpc) {
|
||||
case 'OPEN_API': {
|
||||
if (!msg.path) throw new ExtensionError('UNKNOWN', '缺少 path');
|
||||
data = await openApiRequest(msg.path, {
|
||||
method: msg.method || 'GET',
|
||||
body: msg.body,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'GET_SETTINGS':
|
||||
data = await getSettings();
|
||||
break;
|
||||
case 'SAVE_SETTINGS':
|
||||
data = await saveSettings(msg.patch ?? {});
|
||||
break;
|
||||
default:
|
||||
throw new ExtensionError('UNKNOWN', `未知 RPC:${(msg as { rpc: string }).rpc}`);
|
||||
}
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: true,
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
const err =
|
||||
error instanceof ExtensionError
|
||||
? error
|
||||
: new ExtensionError(
|
||||
'UNKNOWN',
|
||||
error instanceof Error ? error.message : '桥接处理失败',
|
||||
);
|
||||
reply({
|
||||
source: ECBI_SHELL_SOURCE,
|
||||
type: 'RPC_RESULT',
|
||||
requestId: msg.requestId,
|
||||
ok: false,
|
||||
error: { code: err.code, message: err.message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function startBridgeHost(): void {
|
||||
if (started) return;
|
||||
started = true;
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data;
|
||||
|
||||
if (isBridgeRpcRequest(data)) {
|
||||
void handleRpc(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBridgeFeatureEvent(data)) {
|
||||
if (data.event === 'closed') {
|
||||
clearActiveIfFeature(data.featureId);
|
||||
}
|
||||
notifyFeatureEvent(data.featureId, data.event);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/** 壳(isolated)↔ 功能(main world)postMessage 协议 */
|
||||
|
||||
export const ECBI_SHELL_SOURCE = 'ecbi-shell';
|
||||
export const ECBI_FEATURE_SOURCE = 'ecbi-feature';
|
||||
|
||||
export type BridgeRpcType = 'OPEN_API' | 'GET_SETTINGS' | 'SAVE_SETTINGS';
|
||||
|
||||
export interface BridgeRpcRequest {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'RPC';
|
||||
rpc: BridgeRpcType;
|
||||
requestId: string;
|
||||
path?: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
patch?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BridgeRpcResult {
|
||||
source: typeof ECBI_SHELL_SOURCE;
|
||||
type: 'RPC_RESULT';
|
||||
requestId: string;
|
||||
ok: boolean;
|
||||
data?: unknown;
|
||||
error?: { code: string; message: string };
|
||||
}
|
||||
|
||||
export interface BridgeFeatureEvent {
|
||||
source: typeof ECBI_FEATURE_SOURCE;
|
||||
type: 'FEATURE_EVENT';
|
||||
featureId: string;
|
||||
event: 'closed' | 'minimized' | 'restored';
|
||||
}
|
||||
|
||||
export type BridgeIncoming = BridgeRpcRequest | BridgeFeatureEvent;
|
||||
|
||||
export function isBridgeRpcRequest(data: unknown): data is BridgeRpcRequest {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeRpcRequest;
|
||||
return msg.source === ECBI_FEATURE_SOURCE && msg.type === 'RPC' && typeof msg.requestId === 'string';
|
||||
}
|
||||
|
||||
export function isBridgeFeatureEvent(data: unknown): data is BridgeFeatureEvent {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
const msg = data as BridgeFeatureEvent;
|
||||
return (
|
||||
msg.source === ECBI_FEATURE_SOURCE &&
|
||||
msg.type === 'FEATURE_EVENT' &&
|
||||
typeof msg.featureId === 'string'
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Main world 适配:把 Open API / chrome.storage 换成 postMessage RPC。
|
||||
* 功能包 IIFE 加载时调用 installMainWorldAdapters()。
|
||||
*/
|
||||
import { ExtensionError } from '@/shared/errors';
|
||||
import { setOpenApiRequestOverride } from '@/api/client';
|
||||
import { setSettingsOverride, type ExtensionSettings } from '@/storage/settings';
|
||||
|
||||
import {
|
||||
ECBI_FEATURE_SOURCE,
|
||||
ECBI_SHELL_SOURCE,
|
||||
type BridgeRpcResult,
|
||||
type BridgeRpcType,
|
||||
} from './bridgeProtocol';
|
||||
|
||||
const RPC_TIMEOUT_MS = 30_000;
|
||||
|
||||
function postRpc<T>(rpc: BridgeRpcType, payload: Record<string, unknown> = {}): Promise<T> {
|
||||
const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
reject(new ExtensionError('NETWORK_ERROR', `桥接超时(${rpc})`));
|
||||
}, RPC_TIMEOUT_MS);
|
||||
|
||||
function onMessage(event: MessageEvent) {
|
||||
if (event.source !== window) return;
|
||||
const data = event.data as BridgeRpcResult | undefined;
|
||||
if (!data || data.source !== ECBI_SHELL_SOURCE || data.type !== 'RPC_RESULT') return;
|
||||
if (data.requestId !== requestId) return;
|
||||
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('message', onMessage);
|
||||
|
||||
if (!data.ok) {
|
||||
reject(
|
||||
new ExtensionError(
|
||||
(data.error?.code as never) || 'UNKNOWN',
|
||||
data.error?.message || '桥接调用失败',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve(data.data as T);
|
||||
}
|
||||
|
||||
window.addEventListener('message', onMessage);
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'RPC',
|
||||
rpc,
|
||||
requestId,
|
||||
...payload,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
export function installMainWorldAdapters(): void {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
|
||||
setOpenApiRequestOverride(async <T,>(path: string, init: RequestInit = {}) => {
|
||||
const method = (init.method || 'GET').toUpperCase();
|
||||
const body = typeof init.body === 'string' ? init.body : undefined;
|
||||
return postRpc<T>('OPEN_API', { path, method, body });
|
||||
});
|
||||
|
||||
setSettingsOverride({
|
||||
get: () => postRpc<ExtensionSettings>('GET_SETTINGS'),
|
||||
save: (patch) =>
|
||||
postRpc<ExtensionSettings>('SAVE_SETTINGS', {
|
||||
patch: patch as Record<string, unknown>,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function emitFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
window.postMessage(
|
||||
{
|
||||
source: ECBI_FEATURE_SOURCE,
|
||||
type: 'FEATURE_EVENT',
|
||||
featureId,
|
||||
event,
|
||||
},
|
||||
'*',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** 通过 Background 向页面 MAIN world 注入/调用功能脚本(绕过页面 CSP) */
|
||||
|
||||
interface BgResponse {
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
function sendToBackground(message: unknown): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.runtime.sendMessage(message, (response: BgResponse | undefined) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
reject(new Error(chrome.runtime.lastError.message));
|
||||
return;
|
||||
}
|
||||
if (!response?.ok) {
|
||||
reject(new Error(response?.message || 'Background 执行失败'));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function injectMainWorldScript(code: string): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'INJECT_MAIN_SCRIPT',
|
||||
payload: { code },
|
||||
});
|
||||
}
|
||||
|
||||
export async function callMainWorldFeature(
|
||||
featureId: string,
|
||||
action: 'mount' | 'unmount',
|
||||
): Promise<void> {
|
||||
await sendToBackground({
|
||||
type: 'CALL_MAIN_FEATURE',
|
||||
payload: { featureId, action },
|
||||
});
|
||||
}
|
||||
@@ -1,40 +1,81 @@
|
||||
import { pddAdFeeEmbeddedFeature } from '@/features/pdd-ad-fee/embedded';
|
||||
import type { FeatureHandle, FeatureModule, FeatureMountContext } from '@/features/runtime/types';
|
||||
|
||||
const embeddedModules: Record<string, FeatureModule> = {
|
||||
[pddAdFeeEmbeddedFeature.id]: pddAdFeeEmbeddedFeature,
|
||||
};
|
||||
import type { FeatureHandle } from '@/features/runtime/types';
|
||||
import {
|
||||
callMainWorldFeature,
|
||||
injectMainWorldScript,
|
||||
} from '@/features/runtime/mainWorldInject';
|
||||
|
||||
let active: { id: string; handle: FeatureHandle } | null = null;
|
||||
|
||||
type FeatureEventListener = (
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
) => void;
|
||||
|
||||
const listeners = new Set<FeatureEventListener>();
|
||||
|
||||
export function onFeatureEvent(listener: FeatureEventListener): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function notifyFeatureEvent(
|
||||
featureId: string,
|
||||
event: 'closed' | 'minimized' | 'restored',
|
||||
): void {
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener(featureId, event);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getActiveFeatureId(): string | null {
|
||||
return active?.id ?? null;
|
||||
}
|
||||
|
||||
export async function mountFeature(
|
||||
featureId: string,
|
||||
ctx: FeatureMountContext = { featureId },
|
||||
): Promise<void> {
|
||||
export function clearActiveIfFeature(featureId: string): void {
|
||||
if (active?.id === featureId) {
|
||||
return;
|
||||
active = null;
|
||||
}
|
||||
await unmountActiveFeature();
|
||||
}
|
||||
|
||||
const mod = embeddedModules[featureId];
|
||||
if (!mod) {
|
||||
throw new Error(`功能「${featureId}」未在壳内注册,请更新扩展或检查远程清单`);
|
||||
export async function mountFeature(featureId: string, code: string): Promise<void> {
|
||||
if (!code?.trim()) {
|
||||
throw new Error('缺少远程功能脚本,无法挂载');
|
||||
}
|
||||
const handle = await mod.mount({ ...ctx, featureId });
|
||||
active = { id: featureId, handle };
|
||||
if (active?.id === featureId) {
|
||||
// 同一功能重新打开:先卸再挂,确保用最新脚本
|
||||
await unmountActiveFeature();
|
||||
} else {
|
||||
await unmountActiveFeature();
|
||||
}
|
||||
|
||||
await injectMainWorldScript(code);
|
||||
await callMainWorldFeature(featureId, 'mount');
|
||||
|
||||
active = {
|
||||
id: featureId,
|
||||
handle: {
|
||||
unmount: async () => {
|
||||
await callMainWorldFeature(featureId, 'unmount');
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function unmountActiveFeature(): Promise<void> {
|
||||
if (!active) return;
|
||||
const current = active;
|
||||
active = null;
|
||||
await current.handle.unmount();
|
||||
try {
|
||||
await current.handle.unmount();
|
||||
} catch {
|
||||
// 页面可能已刷新,忽略
|
||||
}
|
||||
}
|
||||
|
||||
export function listEmbeddedFeatureIds(): string[] {
|
||||
return Object.keys(embeddedModules);
|
||||
export function isFeatureUiVisible(): boolean {
|
||||
return active != null;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export interface ExtensionFeatureItem {
|
||||
entry: string;
|
||||
/** 脚本 sha256(hex),可选;有则下载后校验 */
|
||||
sha256?: string;
|
||||
/** extension=壳内嵌入模块;main=注入页面(远期) */
|
||||
/** main=页面 MAIN world 执行(可热更新);extension=仅壳内(已弃用) */
|
||||
executionWorld?: 'extension' | 'main';
|
||||
}
|
||||
|
||||
|
||||
@@ -125,9 +125,9 @@ async function handleOpenFeature(item: ExtensionFeatureItem) {
|
||||
? `远程脚本已校验(${item.version})`
|
||||
: `已下载远程脚本(未配置 sha256)`;
|
||||
|
||||
await mountFeatureOnPage(item.id);
|
||||
await mountFeatureOnPage(item.id, remote.code);
|
||||
activeFeatureId.value = item.id;
|
||||
statusText.value = `已打开:${item.name}`;
|
||||
statusText.value = `已打开:${item.name}(远程脚本)`;
|
||||
} catch (error) {
|
||||
errorText.value = toUserMessage(error);
|
||||
} finally {
|
||||
|
||||
@@ -49,10 +49,13 @@ export async function getFloatingPanelState(): Promise<{ visible: boolean }> {
|
||||
return sendToActiveTab<{ visible: boolean }>({ type: 'GET_FLOATING_PANEL_STATE' });
|
||||
}
|
||||
|
||||
export async function mountFeatureOnPage(featureId: string): Promise<{ featureId: string | null }> {
|
||||
export async function mountFeatureOnPage(
|
||||
featureId: string,
|
||||
code: string,
|
||||
): Promise<{ featureId: string | null }> {
|
||||
return sendToActiveTab<{ featureId: string | null }>({
|
||||
type: 'MOUNT_FEATURE',
|
||||
payload: { featureId },
|
||||
payload: { featureId, code },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ export type ExtensionMessage =
|
||||
| { type: 'TOGGLE_FLOATING_PANEL' }
|
||||
| { type: 'SET_FLOATING_PANEL'; payload: { visible: boolean } }
|
||||
| { type: 'GET_FLOATING_PANEL_STATE' }
|
||||
| { type: 'MOUNT_FEATURE'; payload: { featureId: string } }
|
||||
| { type: 'MOUNT_FEATURE'; payload: { featureId: string; code: string } }
|
||||
| { type: 'UNMOUNT_FEATURE' }
|
||||
| { type: 'GET_ACTIVE_FEATURE' }
|
||||
| { type: 'PING' };
|
||||
|
||||
@@ -15,7 +15,23 @@ const DEFAULT_SETTINGS: ExtensionSettings = {
|
||||
apiKey: '',
|
||||
};
|
||||
|
||||
export type SettingsOverride = {
|
||||
get: () => Promise<ExtensionSettings>;
|
||||
save: (patch: Partial<ExtensionSettings>) => Promise<ExtensionSettings>;
|
||||
};
|
||||
|
||||
let settingsOverride: SettingsOverride | null = null;
|
||||
|
||||
/** 功能包在 main world 安装桥接实现时调用 */
|
||||
export function setSettingsOverride(override: SettingsOverride | null): void {
|
||||
settingsOverride = override;
|
||||
}
|
||||
|
||||
export async function getSettings(): Promise<ExtensionSettings> {
|
||||
if (settingsOverride) {
|
||||
return settingsOverride.get();
|
||||
}
|
||||
|
||||
const result = await chrome.storage.local.get(STORAGE_KEY);
|
||||
const raw = result[STORAGE_KEY] as Partial<ExtensionSettings> | undefined;
|
||||
return {
|
||||
@@ -29,6 +45,10 @@ export async function getSettings(): Promise<ExtensionSettings> {
|
||||
export async function saveSettings(
|
||||
patch: Partial<ExtensionSettings>,
|
||||
): Promise<ExtensionSettings> {
|
||||
if (settingsOverride) {
|
||||
return settingsOverride.save(patch);
|
||||
}
|
||||
|
||||
const current = await getSettings();
|
||||
const next: ExtensionSettings = {
|
||||
...current,
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"updatedAt": "2026-08-16T10:21:40.757Z",
|
||||
"updatedAt": "2026-08-16T12:42:11.994Z",
|
||||
"features": [
|
||||
{
|
||||
"id": "pdd-ad-fee",
|
||||
"name": "拼多多商品推广费同步",
|
||||
"version": "0.1.0",
|
||||
"description": "从推广总览读取单日总花费并同步到 BI(壳内嵌入执行;远程包用于版本校验)",
|
||||
"version": "0.2.0",
|
||||
"description": "从推广总览读取单日总花费并同步到 BI(MAIN world 远程脚本,更新后端静态资源即可热更新)",
|
||||
"matchUrlPatterns": [
|
||||
"*://yingxiao.pinduoduo.com/*",
|
||||
"https://yingxiao.pinduoduo.com/"
|
||||
],
|
||||
"entry": "pdd-ad-fee.js",
|
||||
"sha256": "56dc0b6672a9cac6a7cffa8ee4139dc31a2bce37975d8a57b67f6a0e77221c6c",
|
||||
"executionWorld": "extension"
|
||||
"sha256": "6bd6e3ac7ca697fe9f6dd67b1cf17013959981c6e7cae8d95d175c95325071ed",
|
||||
"executionWorld": "main"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user