feat(semi-auto): 客户链接按平台严格绑定,注入后统一由前端打开指定页

This commit is contained in:
2026-11-17 17:27:19 +08:00
parent 7bd5b8bade
commit 77e1c69a2b
13 changed files with 459 additions and 56 deletions
+12 -2
View File
@@ -169,12 +169,22 @@ function OrderServiceApplication() {
function CustomerFulfillmentApplication() {
useClearStrayHash()
// 非标准子路径也按首段路径绑定平台,避免 /c/.../extra 这类地址绕过严格绑定。
const prefix = window.location.pathname.split('/').filter(Boolean)[0]
const wildcardPlatform = prefix === 'c' ? 'huya' : prefix === 'd' ? 'weibo' : undefined
return (
<BrowserRouter>
<Suspense fallback={<RouteLoading />}>
<Routes>
<Route path="/c/:orderNo" element={<CustomerFulfillmentPage />} />
<Route path="*" element={<CustomerFulfillmentPage />} />
<Route path="/c/:orderNo" element={<CustomerFulfillmentPage expectedPlatform="huya" />} />
<Route
path="/d/:orderNo"
element={<CustomerFulfillmentPage expectedPlatform="weibo" />}
/>
<Route
path="*"
element={<CustomerFulfillmentPage expectedPlatform={wildcardPlatform} />}
/>
</Routes>
</Suspense>
</BrowserRouter>
@@ -33,6 +33,7 @@ import {
type DevMockSemiAutoResult,
type DevSemiAutoIntegrationResult,
} from '@/services/admin'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
export default function AdminDevMockPage() {
const { message } = App.useApp()
@@ -109,6 +110,14 @@ export default function AdminDevMockPage() {
})
const defaultOrderNo = useMemo(() => lastCreate?.orderNo || '', [lastCreate?.orderNo])
// 页面展示按平台重新生成规范路径,避免历史 Mock 响应里的 customerPath 仍是 /c。
const semiAutoCustomerPath = lastSemiAuto
? buildCustomerFulfillmentPath(lastSemiAuto.orderNo, lastSemiAuto.semiAutoPlatform) ||
lastSemiAuto.customerPath
: ''
const semiAutoCustomerUrl = semiAutoCustomerPath
? `${window.location.origin}${semiAutoCustomerPath}`
: ''
if (statusQuery.isLoading) {
return (
@@ -347,32 +356,22 @@ export default function AdminDevMockPage() {
<Col span={24}>
<Typography.Text type="secondary">客户履约入口</Typography.Text>
<div>
<Typography.Link
href={`${window.location.origin}${lastSemiAuto.customerPath}`}
target="_blank"
rel="noreferrer"
>
<Typography.Link href={semiAutoCustomerUrl} target="_blank" rel="noreferrer">
<LinkOutlined /> {window.location.origin}
{lastSemiAuto.customerPath}
{semiAutoCustomerPath}
</Typography.Link>
</div>
<Space style={{ marginTop: 8 }} wrap>
<Button
icon={<CopyOutlined />}
onClick={async () => {
await navigator.clipboard.writeText(
`${window.location.origin}${lastSemiAuto.customerPath}`,
)
await navigator.clipboard.writeText(semiAutoCustomerUrl)
message.success('已复制客户履约链接')
}}
>
复制客户链接
</Button>
<Button
type="primary"
href={`${window.location.origin}${lastSemiAuto.customerPath}`}
target="_blank"
>
<Button type="primary" href={semiAutoCustomerUrl} target="_blank">
打开客户页
</Button>
</Space>
@@ -27,7 +27,7 @@ import {
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import ImageUpload from '@/components/files/ImageUpload'
import PageHeader from '@/components/admin/PageHeader'
@@ -47,6 +47,8 @@ import {
import type { SemiAutoTask } from '@/types/admin/semi-auto'
import type { UploadedFile } from '@/types/worker-platform'
import { formatAdminDateTime } from '@/utils/admin-time'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
import { resolvePostInjectionUrl } from '@/utils/semi-auto-injection'
const { Text } = Typography
@@ -87,6 +89,15 @@ type CompleteFormValues = {
costYuan?: number
}
const INJECTION_FOLLOW_UP_TIMEOUT_MS = 30_000
type PendingInjection = {
taskId: number
platform: SemiAutoTask['platform']
popup: Window | null
timeoutId: number
}
export default function AdminSemiAutoTasksPage() {
const { message, modal } = App.useApp()
const queryClient = useQueryClient()
@@ -100,6 +111,7 @@ export default function AdminSemiAutoTasksPage() {
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
const [completeForm] = Form.useForm<CompleteFormValues>()
const pendingInjectionRef = useRef<PendingInjection | null>(null)
const params = useMemo(
() => ({
@@ -137,25 +149,78 @@ export default function AdminSemiAutoTasksPage() {
const handleResult = (event: Event) => {
const detail = (event as CustomEvent<string>).detail
if (typeof detail !== 'string') return
let result: { ok?: boolean; written?: number; error?: string }
try {
const result = JSON.parse(detail) as {
ok?: boolean
written?: number
error?: string
}
if (!result || typeof result !== 'object') return
if (result.ok) {
message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`)
} else {
message.error(result.error || '浏览器登录态注入失败')
}
result = JSON.parse(detail) as { ok?: boolean; written?: number; error?: string }
} catch {
// 忽略其他页面事件
return
}
if (!result || typeof result !== 'object') return
const pending = pendingInjectionRef.current
if (result.ok) {
message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`)
if (!pending) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
const targetUrl = resolvePostInjectionUrl(pending.platform)
const popup = pending.popup
if (!targetUrl) {
if (popup && !popup.closed) popup.close()
return
}
if (popup && !popup.closed) {
try {
popup.location.href = targetUrl
popup.focus()
return
} catch {
// 占位页已被关闭或无法导航:先关掉残留标签,再用 window.open 兜底。
try {
popup.close()
} catch {
// 关闭失败不影响继续打开目标页。
}
}
}
const opened = window.open(targetUrl, '_blank')
if (opened) {
opened.focus()
return
}
modal.info({
title: '注入成功',
content: (
<span>
浏览器拦截了自动打开的新标签页,请
<a href={targetUrl} target="_blank" rel="noreferrer">
点击这里打开平台页面
</a>
。
</span>
),
})
return
}
message.error(result.error || '浏览器登录态注入失败')
if (!pending) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
}
window.addEventListener('huya-exchange-result', handleResult)
return () => window.removeEventListener('huya-exchange-result', handleResult)
}, [message])
}, [message, modal])
// 页面卸载时清理未完成的占位页,避免留下空白标签。
useEffect(() => {
return () => {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
}, [])
const syncMutation = useMutation({
mutationFn: (taskId: number) => syncAdminSemiAutoTask(taskId),
@@ -175,12 +240,33 @@ export default function AdminSemiAutoTasksPage() {
onError: (error) => message.error(error instanceof Error ? error.message : '领取失败'),
})
function cancelPendingInjection() {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
function openInjectionPlaceholder() {
const popup = window.open('about:blank', '_blank')
if (!popup) return null
try {
popup.document.title = '正在注入浏览器登录态'
popup.document.body.textContent = '正在注入浏览器登录态,完成后将自动打开平台页面…'
} catch {
// 占位内容写入失败不影响后续跳转。
}
return popup
}
const injectionMutation = useMutation({
mutationFn: (task: SemiAutoTask) =>
createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)),
onSuccess: (response) => {
const ticket = String(response.data?.ticket || '').trim()
if (!ticket) {
cancelPendingInjection()
message.error('注入票据生成失败')
return
}
@@ -188,10 +274,39 @@ export default function AdminSemiAutoTasksPage() {
message.info('正在注入浏览器登录态,请稍候')
void refreshAll()
},
onError: (error) =>
message.error(error instanceof Error ? error.message : '打开浏览器登录态失败'),
onError: (error) => {
cancelPendingInjection()
message.error(error instanceof Error ? error.message : '打开浏览器登录态失败')
},
})
function startInjection(task: SemiAutoTask) {
if (pendingInjectionRef.current) {
message.warning('上一次注入尚未完成,请稍候')
return
}
// 扩展内容脚本会在白名单页面打标记;没有标记时直接提示,避免空等 30 秒。
if (document.documentElement.dataset.huyaExchangeHelper !== '1') {
message.warning('未检测到浏览器扩展,请启用「虎牙兑换助手」后刷新本页')
return
}
const popup = openInjectionPlaceholder()
const timeoutId = window.setTimeout(() => {
const pending = pendingInjectionRef.current
if (!pending) return
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
message.warning('未检测到注入完成,请确认浏览器扩展已启用后重试')
}, INJECTION_FOLLOW_UP_TIMEOUT_MS)
pendingInjectionRef.current = {
taskId: task.id,
platform: task.platform,
popup,
timeoutId,
}
injectionMutation.mutate(task)
}
const credentialExportMutation = useMutation({
mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId),
onSuccess: (response) => {
@@ -267,7 +382,12 @@ export default function AdminSemiAutoTasksPage() {
}
async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') {
const url = `${window.location.origin}/c/${encodeURIComponent(task.orderNo)}`
const path = buildCustomerFulfillmentPath(task.orderNo, task.platform)
if (!path) {
message.error('订单号为空,无法生成客户链接')
return false
}
const url = `${window.location.origin}${path}`
try {
await navigator.clipboard.writeText(url)
if (successMessage) message.success(successMessage)
@@ -451,7 +571,7 @@ export default function AdminSemiAutoTasksPage() {
icon={<ChromeOutlined />}
disabled={!taskCanUseCredential(task)}
loading={injectionMutation.isPending}
onClick={() => injectionMutation.mutate(task)}
onClick={() => startInjection(task)}
>
注入浏览器
</Button>
@@ -720,7 +840,7 @@ export default function AdminSemiAutoTasksPage() {
icon={<ChromeOutlined />}
disabled={!taskCanUseCredential(detail.task)}
loading={injectionMutation.isPending}
onClick={() => injectionMutation.mutate(detail.task)}
onClick={() => startInjection(detail.task)}
>
注入浏览器
</Button>
@@ -658,7 +658,7 @@ export function ManualSkuConfigPanel() {
name="semiAutoEnabled"
label="启用半自动履约"
valuePropName="checked"
extra="订单进入人工渠道后,客户可通过 /c/订单号 登录平台并完成绑定。"
extra="订单进入人工渠道后,客户可通过专属链接登录平台并完成绑定(虎牙 /c/订单号,微博 /d/订单号)。"
>
<Switch />
</Form.Item>
@@ -8,7 +8,7 @@ import {
import { App, Alert, Button, Image, Input, Modal, Select, Space, Spin } from 'antd'
import QRCode from 'qrcode'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useParams } from 'react-router'
import { useLocation, useNavigate, useParams } from 'react-router'
import {
confirmCustomerBinding,
@@ -36,6 +36,11 @@ import type {
CustomerSemiAutoTask,
} from '@/types/customer-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time'
import {
buildCustomerFulfillmentPath,
resolveCustomerPlatformRedirect,
type CustomerFulfillmentPlatform,
} from '@/utils/customer-fulfillment-link'
import { runWeiboYidunChallenge } from '@/utils/weibo-yidun'
import HuyaChallengeModal from './HuyaChallengeModal'
@@ -46,9 +51,15 @@ const SERVER_ZONE_OPTIONS = ['苹果Q区', '苹果V区', '安卓Q区', '安卓V
/** antd v6 语义化 classNames:让区服下拉弹层用页面深色样式 */
const SERVER_ZONE_SELECT_CLASS_NAMES = { popup: { root: 'customer-collect-dropdown' } }
export default function CustomerFulfillmentPage() {
export default function CustomerFulfillmentPage({
expectedPlatform,
}: {
expectedPlatform?: CustomerFulfillmentPlatform
}) {
const { message, modal } = App.useApp()
const { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>()
const navigate = useNavigate()
const { search, hash } = useLocation()
const orderNo = String(routeOrderNo || '').trim()
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
@@ -79,6 +90,7 @@ export default function CustomerFulfillmentPage() {
const startingBindingRef = useRef(false)
const hydratingBindingRef = useRef(false)
const autoOpenedRoleRef = useRef('')
const redirectingRef = useRef(false)
// Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。
const [bindingSessionExpired, setBindingSessionExpired] = useState(false)
const [bindingLoadError, setBindingLoadError] = useState('')
@@ -100,11 +112,28 @@ export default function CustomerFulfillmentPage() {
try {
const response = await fetchCustomerFulfillment(orderNo)
const nextTasks = response.data || []
setTasks(nextTasks)
const redirectPlatform = resolveCustomerPlatformRedirect(expectedPlatform, nextTasks)
if (redirectPlatform) {
const targetPath = buildCustomerFulfillmentPath(orderNo, redirectPlatform)
if (targetPath && !redirectingRef.current) {
redirectingRef.current = true
void navigate(`${targetPath}${search}${hash}`, { replace: true })
}
return
}
const visibleTasks = expectedPlatform
? nextTasks.filter((task) => task.platform === expectedPlatform)
: nextTasks
if (expectedPlatform && nextTasks.length > 0 && visibleTasks.length === 0) {
setTasks([])
setLoadError('当前链接与订单平台不匹配,请使用对应平台的客户链接')
return
}
setTasks(visibleTasks)
setLoadError('')
setSelectedTaskId((current) => {
if (nextTasks.some((task) => task.id === current)) return current
return nextTasks[0]?.id || 0
if (visibleTasks.some((task) => task.id === current)) return current
return visibleTasks[0]?.id || 0
})
} catch (error) {
if (!silent) {
@@ -115,9 +144,14 @@ export default function CustomerFulfillmentPage() {
if (!silent) setLoading(false)
}
},
[orderNo],
[expectedPlatform, hash, navigate, orderNo, search],
)
// 订单号或平台路由变化后允许重新判定跳转,避免复用组件时上一次的标记卡住。
useEffect(() => {
redirectingRef.current = false
}, [expectedPlatform, orderNo])
useEffect(() => {
void load()
}, [load])
@@ -1,6 +1,58 @@
/** 客户半自动履约入口:/c/:orderNo。 */
export type CustomerFulfillmentPlatform = 'huya' | 'weibo'
/** 客户半自动履约入口:虎牙 /c/:orderNo,微博 /d/:orderNo。 */
export function buildCustomerFulfillmentPath(orderNo: unknown, platform: unknown): string {
const normalizedOrderNo = String(orderNo || '').trim()
if (!normalizedOrderNo) return ''
const prefix =
String(platform || '')
.trim()
.toLowerCase() === 'weibo'
? 'd'
: 'c'
return `/${prefix}/${encodeURIComponent(normalizedOrderNo)}`
}
export function isCustomerFulfillmentPath(pathname: unknown): boolean {
const normalized = String(pathname || '').trim()
if (!normalized.startsWith('/')) return false
return normalized.split(/[?#]/)[0].replace(/\/+$/, '').split('/').filter(Boolean)[0] === 'c'
const first = normalized.split(/[?#]/)[0].replace(/\/+$/, '').split('/').filter(Boolean)[0]
return first === 'c' || first === 'd'
}
/**
* 严格绑定下的自动归一化:当前路径对应平台没有任务、但订单只有另一个平台任务时,
* 返回应跳转的平台;双平台订单返回 null(各路径只展示自己的任务),
* 无任务或平台未知也返回 null。
*/
export function resolveCustomerPlatformRedirect(
expectedPlatform: CustomerFulfillmentPlatform | null | undefined,
tasks: Array<{ platform?: string | null }>,
): CustomerFulfillmentPlatform | null {
if (expectedPlatform !== 'huya' && expectedPlatform !== 'weibo') return null
if (!Array.isArray(tasks) || tasks.length === 0) return null
if (
tasks.some(
(task) =>
String(task.platform || '')
.trim()
.toLowerCase() === expectedPlatform,
)
) {
return null
}
const platforms = new Set(
tasks
.map((task) =>
String(task.platform || '')
.trim()
.toLowerCase(),
)
.filter(
(platform): platform is CustomerFulfillmentPlatform =>
platform === 'huya' || platform === 'weibo',
),
)
if (platforms.size !== 1) return null
return [...platforms][0]
}
@@ -0,0 +1,15 @@
import type { SemiAutoPlatform } from '@/types/admin/semi-auto'
/**
* 注入浏览器成功后自动打开的平台页面。
* 只在客户页/后台侧使用;扩展只负责写入 Cookie,指定平台页由前端占位页打开。
*/
export const POST_INJECTION_URLS: Record<SemiAutoPlatform, string> = {
huya: 'https://m-shop.huya.com/points.html?pagecode=heping_baodian_credit_center_page&sourceId=yellowcarlist&pid=1199650619883&anchorUid=1199650619883&roomid=30596253',
weibo: 'https://vipclub.e.weibo.com/game/homepage?F=bowen_tjg',
}
export function resolvePostInjectionUrl(platform: string | null | undefined): string {
if (platform === 'huya' || platform === 'weibo') return POST_INJECTION_URLS[platform]
return ''
}
@@ -1,17 +1,93 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
import { isCustomerFulfillmentPath } from '../src/utils/customer-fulfillment-link.ts'
import {
buildCustomerFulfillmentPath,
isCustomerFulfillmentPath,
resolveCustomerPlatformRedirect,
} from '../src/utils/customer-fulfillment-link.ts'
test('客户半自动履约入口:/c 命名空间整段命中', () => {
test('客户半自动履约入口:/c 与 /d 命名空间整段命中', () => {
assert.equal(isCustomerFulfillmentPath('/c/263123'), true)
assert.equal(isCustomerFulfillmentPath('/c'), true)
assert.equal(isCustomerFulfillmentPath('/c/a/b'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123'), true)
assert.equal(isCustomerFulfillmentPath('/d'), true)
assert.equal(isCustomerFulfillmentPath('/d/a/b'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123?from=chat'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123#section'), true)
})
test('客户半自动履约入口不误伤相似前缀和其他路径', () => {
assert.equal(isCustomerFulfillmentPath('/claim/x'), false)
assert.equal(isCustomerFulfillmentPath('/customer/x'), false)
assert.equal(isCustomerFulfillmentPath('/admin/c/1'), false)
assert.equal(isCustomerFulfillmentPath('/admin/d/1'), false)
assert.equal(isCustomerFulfillmentPath('/dd/1'), false)
assert.equal(isCustomerFulfillmentPath('c/1'), false)
assert.equal(isCustomerFulfillmentPath('d/1'), false)
})
test('按平台生成客户链接:虎牙 /c、微博 /d', () => {
assert.equal(
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'huya'),
'/c/INTSA1794902905684_360848',
)
assert.equal(
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'weibo'),
'/d/INTSA1794902905684_360848',
)
assert.equal(buildCustomerFulfillmentPath(' INTWB1 ', 'WEIBO'), '/d/INTWB1')
assert.equal(buildCustomerFulfillmentPath('a/b', 'weibo'), '/d/a%2Fb')
assert.equal(buildCustomerFulfillmentPath('', 'weibo'), '')
assert.equal(buildCustomerFulfillmentPath('x', 'unknown'), '/c/x')
})
test('严格绑定:路径平台不匹配时返回应跳转的平台', () => {
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'weibo' }]), 'weibo')
assert.equal(resolveCustomerPlatformRedirect('weibo', [{ platform: 'huya' }]), 'huya')
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'huya' }]), null)
assert.equal(resolveCustomerPlatformRedirect('weibo', [{ platform: 'weibo' }]), null)
assert.equal(
resolveCustomerPlatformRedirect('huya', [{ platform: 'huya' }, { platform: 'weibo' }]),
null,
)
assert.equal(
resolveCustomerPlatformRedirect('weibo', [{ platform: 'huya' }, { platform: 'weibo' }]),
null,
)
assert.equal(resolveCustomerPlatformRedirect('huya', []), null)
assert.equal(resolveCustomerPlatformRedirect(undefined, [{ platform: 'weibo' }]), null)
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'unknown' }]), null)
assert.equal(
resolveCustomerPlatformRedirect('huya', [{ platform: 'weibo' }, { platform: 'unknown' }]),
'weibo',
)
})
test('客户页路由与严格绑定接线', async () => {
const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8')
const page = await readFile(
new URL('../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx', import.meta.url),
'utf8',
)
assert.match(app, /path="\/c\/:orderNo"/)
assert.match(app, /expectedPlatform="huya"/)
assert.match(app, /path="\/d\/:orderNo"/)
assert.match(app, /expectedPlatform="weibo"/)
assert.match(page, /resolveCustomerPlatformRedirect/)
assert.match(page, /buildCustomerFulfillmentPath/)
assert.match(page, /task\.platform === expectedPlatform/)
})
test('开发 Mock 页按平台重新生成客户路径', async () => {
const page = await readFile(
new URL('../src/pages/admin/AdminDevMockPage.tsx', import.meta.url),
'utf8',
)
assert.match(page, /buildCustomerFulfillmentPath/)
assert.match(page, /semiAutoCustomerPath/)
assert.match(page, /semiAutoCustomerUrl/)
})
@@ -0,0 +1,47 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import { POST_INJECTION_URLS, resolvePostInjectionUrl } from '../src/utils/semi-auto-injection.ts'
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), '../src/pages/admin/AdminSemiAutoTasksPage.tsx'),
'utf8',
)
test('注入完成后打开对应平台页面', () => {
assert.equal(resolvePostInjectionUrl('huya'), POST_INJECTION_URLS.huya)
assert.equal(resolvePostInjectionUrl('weibo'), POST_INJECTION_URLS.weibo)
assert.match(POST_INJECTION_URLS.huya, /^https:\/\/m-shop\.huya\.com\/points\.html\?/)
assert.match(
POST_INJECTION_URLS.weibo,
/^https:\/\/vipclub\.e\.weibo\.com\/game\/homepage\?F=bowen_tjg$/,
)
assert.equal(resolvePostInjectionUrl('other'), '')
assert.equal(resolvePostInjectionUrl(null), '')
})
test('注入按钮预开新标签页,完成后跳转,失败/超时关闭', () => {
assert.ok(source.includes("window.open('about:blank', '_blank')"))
assert.ok(source.includes('function startInjection('))
assert.ok(source.includes('onClick={() => startInjection(task)}'))
assert.ok(source.includes('onClick={() => startInjection(detail.task)}'))
assert.ok(source.includes('huya-exchange-result'))
assert.ok(source.includes('resolvePostInjectionUrl(pending.platform)'))
assert.ok(source.includes('popup.location.href = targetUrl'))
assert.ok(source.includes('popup.focus()'))
assert.ok(source.includes("const opened = window.open(targetUrl, '_blank')"))
// 占位页无法导航时,先关闭残留标签再走 window.open 兜底,避免留下空白页。
const jumpIndex = source.indexOf('popup.location.href = targetUrl')
const fallbackIndex = source.indexOf("const opened = window.open(targetUrl, '_blank')")
assert.ok(jumpIndex >= 0 && fallbackIndex > jumpIndex)
assert.ok(source.slice(jumpIndex, fallbackIndex).includes('popup.close()'))
assert.ok(source.includes('pending.popup.close()'))
assert.ok(source.includes('INJECTION_FOLLOW_UP_TIMEOUT_MS'))
assert.ok(source.includes('未检测到注入完成'))
assert.ok(source.includes('上一次注入尚未完成'))
assert.ok(source.includes("dataset.huyaExchangeHelper !== '1'"))
assert.ok(source.includes('未检测到浏览器扩展'))
})