import webview from '@ohos.web.webview';
import { TencentQianWebViewConfig } from '../model/TencentQianWebViewConfig';
import { OnSdkEvent } from '../model/SignCallback';
import { UserAgentInjectFailedEvent } from '../model/SdkEvent';
import { TencentQianWebView } from '../TencentQianWebView';
/**
* UA 注入器。
*
* 在 controller 绑定 Web 组件之后(`onControllerAttached` 时机),
* 将 SDK UA 标识 `qianwv/<version>` 与客户附加段拼接到默认 UA 之后。
* 注入失败时通过 `UserAgentInjectFailed` 事件回报,不抛异常、不影响主流程。
*/
export class UserAgentInjector {
/**
* 注入 UA。
*
* @param controller 已 attach 的 WebviewController
* @param config 客户配置
* @param onEvent 可选的事件回调(注入失败时上报)
*/
public static inject(
controller: webview.WebviewController,
config: TencentQianWebViewConfig,
onEvent?: OnSdkEvent
): void {
if (!config.injectUserAgent) {
return;
}
try {
const defaultUa: string = controller.getUserAgent();
let combined: string = defaultUa + ' ' + 'qianwv/' + TencentQianWebView.sdkVersion();
const extra: string = config.userAgentExtra;
if (extra !== null && extra !== undefined && extra.length > 0) {
combined = combined + ' ' + extra;
}
controller.setCustomUserAgent(combined);
} catch (e) {
const reason: string = (e instanceof Error) ? e.message : String(e);
if (onEvent !== undefined) {
onEvent(new UserAgentInjectFailedEvent(reason));
}
}
}
// ArkTS 类禁止实例化
private constructor() {}
}
|