app打开微信url scheme



// 在页面方法中
    addEnterpriseWeChat() {
        console.log('addEnterpriseWeChat');
        // 企业微信 URL Scheme
        const enterpriseWeChatUrl = 'wxwork://work.weixin.qq.com/ca/cawcdec67ef479c17d';
        // 微信添加联系人 URL Schemeh
        const weChatAddUrl = 'weixin://dl/add';
        // 普通微信 URL Scheme
        const weChatUrl = 'weixin://';

        // 尝试打开企业微信
        this.openScheme(enterpriseWeChatUrl).then(() => {
            console.log('成功打开企业微信');
        }).catch(() => {
            // 如果企业微信打开失败,尝试微信添加联系人
            return this.openScheme(weChatAddUrl);
        }).then(() => {
            console.log('成功打开微信添加联系人');
        }).catch(() => {
            // 如果添加联系人失败,尝试普通微信
            return this.openScheme(weChatUrl);
        }).then(() => {
            console.log('成功打开微信');
        }).catch(() => {
            // 所有方案都失败,提示用户
            uni.showModal({
                title: '提示',
                content: '未检测到微信或企业微信,请先安装应用',
                showCancel: false
            });
        });
    },

    // 封装打开 URL Scheme 的方法
    openScheme(url) {
        return new Promise((resolve, reject) => {
            // #ifdef APP-PLUS
            plus.runtime.openURL(url, (res) => {
                resolve();
            }, (err) => {
                reject(err);
            });
            // #endif

            // #ifdef H5
            // H5 端尝试使用 window.location
            try {
                window.location.href = url;
                setTimeout(() => {
                    // 如果一段时间后还在当前页面,认为打开失败
                    reject(new Error('打开失败'));
                }, 2000);
            } catch (error) {
                reject(error);
            }
            // #endif
        });
    }

Comments

No comments yet. Why don’t you start the discussion?

发表回复