webview-screenshot-comparison.uvue 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
<template>
  <web-view id="webview-screenshot" class="webview-screenshot" :src="src" @loaded="loaded" @error="error">
  </web-view>
  <text style="display: none"></text>
</template>

<script>
  export default {
    data() {
      return {
        // example baseSrc: 'http://ip:port/#/',
        baseSrc: '',
        src: '',
        webviewContext: null as WebviewContext | null,
        isLoaded: false,
        needRemoveWebHead: false,
      }
    },
    onReady() {
      this.webviewContext = uni.createWebviewContext('webview-screenshot', this)
    },
    methods: {
      removeWebHead() {
        this.webviewContext?.evalJS(`document.querySelector('uni-page-head').style.display='none'`);
      },
      appendWebHeadPlaceholder() {
        this.webviewContext?.evalJS(`
    const hasWebHeadPlaceholder = document.querySelector('.web-head-placeholder-for-screenshot-comparison');
    if (hasWebHeadPlaceholder) {
      return;
    }
    const webHeadPlaceholder = document.createElement('div');
    webHeadPlaceholder.style.height = '52px';
    webHeadPlaceholder.style.backgroundColor = '#007aff';
    webHeadPlaceholder.classList.add('web-head-placeholder-for-screenshot-comparison');
    const uniPage = document.querySelector('uni-page');
    const uniPageHead = document.querySelector('uni-page-head');
    uniPage.insertBefore(webHeadPlaceholder, uniPageHead);
    `);
      },
      loaded() {
        this.isLoaded = true
        if (this.needRemoveWebHead) {
          this.removeWebHead();
        } else {
          this.appendWebHeadPlaceholder();
        }
      },
      error(event : WebViewErrorEvent) {
        console.log('webview load error', JSON.stringify(event.detail));
      }
    }
  }
</script>
<style>
  .webview-screenshot {
    flex: 1;
  }
</style>