plus-runtime.uts 2.33 KB
/**
 * plus.runtime 的 uni-app x 替代实现
 * 用于获取应用信息、打开URL等
 */

// #ifdef APP
// 打开外部 URL 使用官方 UTS 插件 uts-openSchema
// 插件文档:https://ext.dcloud.net.cn/plugin?id=17828
import { openSchema } from "@/uni_modules/uts-openSchema";
// #endif

// 应用信息类型
type AppInfo = {
	version: string;
	appid: string;
};

/**
 * 获取应用版本号
 */
export function getAppVersion(): string {
	// 优先使用 uni.getAppBaseInfo(官方推荐,跨端)
	// https://doc.dcloud.net.cn/uni-app-x/api/getAppBaseInfo.html
	try {
		// #ifdef APP || WEB
		const baseInfo = uni.getAppBaseInfo();
		if (baseInfo != null) {
			const ver = baseInfo.appVersion;
			// 避免直接访问 length 引发已知编译问题,使用字符串比较
			if (ver != null && ver != "") {
				return ver;
			}
		}
	// #endif
	} catch (e: any) {
		console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败: ", e);
	}

	// 其它平台或获取失败时返回空字符串,由上层决定是否展示
	return "";
}

/**
 * 获取应用ID(appid)
 */
export function getAppId(): string {
	// 优先使用 uni.getAppBaseInfo(跨端)
	try {
		// #ifdef APP || WEB
		const baseInfo = uni.getAppBaseInfo();
		if (baseInfo != null) {
			const id = baseInfo.appId;
			if (id != null && id != "") {
				return id;
			}
		}
	// #endif
	} catch (e: any) {
		console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败: ", e);
	}

	return "";
}

/**
 * 打开外部URL
 * @param url 要打开的URL
 */
export function openURL(url: string): void {
	if (url == null || url.length == 0) {
		console.error("[plus-runtime] URL不能为空");
		return;
	}

	// App 端:使用 uts-openSchema 插件打开外部链接
	// https://ext.dcloud.net.cn/plugin?id=17828
	// #ifdef APP
	try {
		openSchema(url);
		return;
	} catch (e: any) {
		console.error("[plus-runtime] 使用 openSchema 打开 URL 失败: ", e, " url=", url);
	}
	// #endif

	// 其它平台或兜底逻辑:H5 使用 window.open
	// #ifndef APP
	if (typeof window != "undefined") {
		window.open(url, "_blank");
	}
	// #endif
}

/**
 * 获取应用信息(版本号、appid等)
 * 注意:在 uni-app x 中需要通过 UTS 插件获取完整信息
 */
export function getAppInfo(): AppInfo {
	return {
		version: getAppVersion(),
		appid: getAppId()
	};
}