SoFunction
Updated on 2025-04-13

Simple steps for h5 communication between app and webview in uni-app

Summary:

1. The page using webview needs to be nvue, otherwise there is no () method;

2. You need to install npm i y_uniwebview yourself. The official introduction of /dev/uni-app/.1.5. scripts with conflicts will be reported, and an error will be reported.

The first step is to install the y_uniwebview plug-in in the h5 project

Install: npm i y_uniwebview
Introduced: import y_uni from "y_uniwebview"

Step 2: h5 code, receive app information and send information to app

<template>
  <view class="avatar-uploader">
    <view>
      <button @click="postMessage">TowardsappSend a message</button>
    </view>
    <view>
      Receivedappinformation:{{ appMsg }}
    </view>
  </view>
</template>
<script lang="ts" setup>

import y_uni from "y_uniwebview"
import { ref } from 'vue';

const appMsg = ref('');

// App information trigger method = (val) => {
   = val
  ('The data sent by the app ---', val)
}

let count = 0;

// Send information to the appfunction postMessage(type) {
  ('h5Send Message');
  // Send information  y_uni.({
    data: {
      msg: `h5information ${count++} Second-rate`
    }
  });
}

</script>

Step 3, app page, receive h5 information and send information to h5

Note that nvue is needed here, otherwise there will be no () to cause an error

<template>
    <view>
        <button  @click="postMsg">
            Towardsh5Send a message
        </button>
        <view>
            Receivedh5information:{{h5Msg}}
        </view>
    </view>
    <br>
    <web-view
            ref="sWebViewRef"
            src="http://192.168.31.93/" style="" :style="webViewStyle"
            @on-post-message="handleMessage"
    ></web-view>
</template>

<script setup>
    import {computed, ref} from 'vue';

    const sWebViewRef = ref()

    const h5Msg = ref('');

    // Receive h5 information    function handleMessage(event) {
        // Receive messages sent by webview         = [0].msg;
        ('Received h5 message: ' + h5Msg);
    }
    
    let count = 0;

    // Send information to h5    function postMsg(msg) {
        ('App sends information')
        (`appCallBack('appinformation ${count++} Second-rate')`)
    }

    const webViewStyle = computed(() => {
        let width = 0;
        let height = 0;
        ({
            // Get specific information about the current device            success: sysinfo => {
                width =  - 100;
                height =  - 100;
            }
        })
        return {
            width: width + 'px', height: height + 'px'
        }
    })
</script>

Summarize

This is the article about h5 communication between app and webview in uni-app. For more information about h5 communications for uni-app app and webview, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!