UNPKG

@tarojs/components

Version:
73 lines (69 loc) • 2.18 kB
import { r as registerInstance, c as createEvent, h } from './index-0004ce39.js'; const indexCss = "iframe{border:none}.taro-webview{z-index:999;width:100%;height:100%;position:fixed;top:0;bottom:0}"; const hasWindow = typeof window !== 'undefined' && typeof window.addEventListener === 'function'; const webViewInstances = new Set(); let messageListenerAttached = false; function handleWindowMessage(event) { webViewInstances.forEach(instance => { instance.handleMessage(event); }); } function attachGlobalMessageListener() { if (!hasWindow || messageListenerAttached) return; window.addEventListener('message', handleWindowMessage); messageListenerAttached = true; } function detachGlobalMessageListenerIfNeeded() { if (!hasWindow || !messageListenerAttached) return; if (webViewInstances.size > 0) return; window.removeEventListener('message', handleWindowMessage); messageListenerAttached = false; } const WebView = class { constructor(hostRef) { registerInstance(this, hostRef); this.onLoad = createEvent(this, "load", 7); this.onError = createEvent(this, "error", 7); this.onMessage = createEvent(this, "message", 7); this.src = undefined; } componentDidLoad() { webViewInstances.add(this); attachGlobalMessageListener(); } disconnectedCallback() { webViewInstances.delete(this); detachGlobalMessageListenerIfNeeded(); } handleMessage(event) { var _a; const iframeWindow = (_a = this.iframe) === null || _a === void 0 ? void 0 : _a.contentWindow; if (!iframeWindow || event.source !== iframeWindow) return; const { src, onMessage } = this; if (!onMessage) return; onMessage.emit({ data: event.data, origin: event.origin, src }); } render() { const { src, onLoad, onError } = this; return (h("iframe", { ref: el => { this.iframe = el; }, class: 'taro-webview', onLoad: (e) => { e.stopPropagation(); onLoad.emit({ src }); }, onError: (e) => { e.stopPropagation(); onError.emit({ src }); }, src: src })); } }; WebView.style = indexCss; export { WebView as W };