import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
/**
* 处理外部 App scheme 跳转。
*
* 命中白名单 scheme(如 `weixin://`)时通过 `context.startAbility(Want)` 拉起目标 App。
*/
export class ExternalSchemeHandler {
/**
* 提取 URL 的 scheme(小写)。无法识别返回 ''。
*
* @example schemeOf('weixin://pay/abc') → 'weixin'
*/
public static schemeOf(url: string): string {
if (url === null || url === undefined || url.length === 0) {
return '';
}
const idx: number = url.indexOf(':');
if (idx <= 0) {
return '';
}
return url.substring(0, idx).toLowerCase();
}
/**
* 判断 url 的 scheme 是否在白名单内。
*/
public static isWhitelisted(url: string, whitelist: string[]): boolean {
if (whitelist === null || whitelist === undefined || whitelist.length === 0) {
return false;
}
const scheme: string = ExternalSchemeHandler.schemeOf(url);
if (scheme.length === 0) {
return false;
}
return whitelist.some((w: string) => w.toLowerCase() === scheme);
}
/**
* 尝试拉起外部 App。
*
* @returns true=拉起成功; false=拉起失败(调用方需自行上报)
*/
public static async open(
context: common.UIAbilityContext,
url: string
): Promise<boolean> {
if (context === null || context === undefined) {
return false;
}
try {
const want: Want = {
action: 'ohos.want.action.viewData',
uri: url
};
await context.startAbility(want);
return true;
} catch (_e) {
return false;
}
}
// ArkTS 类禁止实例化
private constructor() {}
}
|