@tarojs/components
Version:
143 lines (142 loc) • 3.48 kB
JavaScript
import { h } from '@stencil/core';
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;
}
export class WebView {
constructor() {
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 is() { return "taro-web-view-core"; }
static get originalStyleUrls() {
return {
"$": ["./style/index.scss"]
};
}
static get styleUrls() {
return {
"$": ["./style/index.css"]
};
}
static get properties() {
return {
"src": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": ""
},
"attribute": "src",
"reflect": false
}
};
}
static get events() {
return [{
"method": "onLoad",
"name": "load",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": ""
},
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
}
}, {
"method": "onError",
"name": "error",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": ""
},
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
}
}, {
"method": "onMessage",
"name": "message",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": ""
},
"complexType": {
"original": "any",
"resolved": "any",
"references": {}
}
}];
}
}