@tarojs/components
Version:
92 lines (87 loc) • 2.78 kB
JavaScript
import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
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 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
constructor() {
super();
this.__registerHost();
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 }));
}
static get style() { return indexCss; }
}, [0, "taro-web-view-core", {
"src": [1]
}]);
function defineCustomElement$1() {
if (typeof customElements === "undefined") {
return;
}
const components = ["taro-web-view-core"];
components.forEach(tagName => { switch (tagName) {
case "taro-web-view-core":
if (!customElements.get(tagName)) {
customElements.define(tagName, WebView);
}
break;
} });
}
const TaroWebViewCore = WebView;
const defineCustomElement = defineCustomElement$1;
export { TaroWebViewCore, WebView as W, defineCustomElement };