提交 4f876718 作者: 方治民

feat: 优化 webview 通用页面组件

上级 5a60b6ea
<script lang="ts" setup>
import URI from 'urijs'
import * as _ from 'lodash-es'
import { isProdMode } from '@/utils/env'
const page = reactive({
security: false,
......@@ -37,9 +39,18 @@
}
// #ifdef APP-PLUS
// 白名单同源检测
if (isSameOrigin(new URI(page.link))) {
// 本地网页或白名单同源检测
if (page.link.startsWith('/hybrid/') || page.link.startsWith('/static/') || isSameOrigin(new URI(page.link))) {
page.security = true
// 延迟获取 webview 对象,插入 js 文件
setTimeout(() => {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const currentWebview = currentPage.$getAppWebview()
const webview = currentWebview.children()[0]
webview.appendJsFile('_www/static/uni.webview.1.5.6.js')
}, 1000)
} else {
// 对于不安全或不信任的网站地址或可能触发 plus API 的来源,采用手动创建 webview 的方式打开
const { windowHeight, statusBarHeight } = uni.getSystemInfoSync()
......@@ -62,7 +73,7 @@
})
// 安全域白名单,防止 APP 环境的意外注入和非法安全调用 plus API 的问题
const allows = ['yiring.com']
const allows = ['yiring.com', 'uniapp.dcloud.io']
// 在安全域白名单中,但仍然需要排除的链接(通常是代理的网站链接)
const denyLinks = []
function isSameOrigin(url: URI) {
......@@ -75,12 +86,26 @@
return regex.test(url.hostname())
})
}
// 监听来自 webview 的消息
const onPostMessage = _.debounce(function (e: { detail: { data: any } }) {
console.warn('onPostMessage', e)
if (!isProdMode()) {
Message.alert(JSON.stringify(e.detail.data))
}
}, 200)
</script>
<template>
<view class="wrap" v-if="page.link">
<template v-if="page.security">
<web-view :src="page.link" :update-title="!page.title" :webview-styles="page.styles" />
<web-view
:src="page.link"
:update-title="!page.title"
:webview-styles="page.styles"
@message="onPostMessage"
/>
</template>
</view>
</template>
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论