H5内嵌iframe,ios长按识别iframe中的小程序二维码识别不出来的问题记录

1 阅读1分钟
  1. iframe postMessage出小程序图片地址给外层H5 window.parent.postMessage( { type: qrCodeUrl, code: 0, msg: '"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD', data: { qrCodeUrl: true, } }, '*', );
  2. 外层H5监听事件,获取到小程序图片地址 onMounted(() => { window.addEventListener("message", handleMessage); });

const handleMessage = (event: MessageEvent) => { // 添加来源验证

const { type, code, msg, data } = event.data; console.log("收到消息msg:", msg); console.log("收到消息type:", type); console.log("收到消息code:", code);

console.log("收到消息data:", data); // 检查 type 是否直接是 qrCodeUrl 变量值 console.log("收到消息:", type === "qrCodeUrl", typeof msg === "string"); // 检查 type 是否直接是 qrCodeUrl 变量值 // if (type === "qrCodeUrl") { // 使用 msg 作为二维码数据,因为base64图片数据在 msg 字段中 if ( typeof msg === "string" && (msg.startsWith("data:image/png;base64,") || msg.startsWith("data:image/jpg;base64,")) ) { state.qrCodeUrl = msg; console.log("收到消息qrCodeUrl:", state.qrCodeUrl); } else { state.qrCodeUrl = ""; }

// } if (type === "goBack") { router.back(); } };

  1. 重点:即使opacity:0,但是微信中拖拽图片还是会导致图片显示出来,透明度为0失效,因此在图片中还要禁止拖拽。一开始使用的pointer-evene:none来禁止拖拽,后来发现这个属性也会导致长按识别动作识别不到 <img v-if="state.qrCodeUrl" :src="state.qrCodeUrl" alt="" class="w-full h-full fixed z-50 top-0 left-0 opacity-0" style="opacity: 0" draggable="false" @dragstart.prevent />