uni-app webview监听当前url

发布时间 2024-01-01 21:39:37作者: 对不起,我要起飞
<template>
    <view>
        <web-view :src="url" @message="getMessage" ref="v"></web-view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                // url: 'https://uniapp.dcloud.io/static/web-view.html',
                url: 'http://localhost:5000/login.html?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dtest%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A5003%252Fcallback.html%26response_type%3Dcode%26scope%3Dopenid%2520profile%2520ms.product%26state%3D38b54b3ed56643d496d287d0782da8f0%26code_challenge%3DElk-mxsrknVQXK-WQ0aGH9OF34Nq2mOSJStoLuKWd84%26code_challenge_method%3DS256%26response_mode%3Dquery'
            }
        },
        onLoad(options) {
            if (options && options.url) {
                this.url = options.url;
            }

            this.listenUrl()
        },
        methods: {
            getMessage(event) {
                uni.showModal({
                    content: JSON.stringify(event.detail),
                    showCancel: false
                });
            },
            listenUrl() {
                var that = this;
                setInterval(() => {
                    var currentUrl = that.getCurrentUrl();
                    var code = that.getCurrentQueryString(currentUrl, 'code');
                    
                    console.log('获取到的code:', code)
                    
                    if (currentUrl.includes("/callback")){
                        console.log('回调咯!!!!!!!!!!!')
                        var navURL = `/pages/component/button?code=${code}`;
                        uni.navigateTo({
                            url: navURL,
                            animationType: 'pop-in'
                        })
                    }
                }, 5000)
            },
            getCurrentQueryString(url, name) {
                var queryString = url.substring(url.indexOf('?'));
                var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
                var r = queryString.substr(1).match(reg);
                if (r != null) {
                    return unescape(r[2]);
                }
                
                return null;
            },
            getCurrentUrl(){
                var pages = getCurrentPages();
                var page = pages[pages.length - 1];
                var currentWebview = page.$getAppWebview();
                var url = currentWebview.children()[0].getURL();
                console.log("=======当前地址======", url);
                
                return url;
            }
        }
    }
    
</script>

<style>

</style>