@mt-kit/utils
Version:
55 lines • 1.62 kB
JavaScript
class IframeMessage {
constructor() {
this.iframe = null;
this.url = null;
// 页面卸载时自动移除 iframe
window.addEventListener("beforeunload", () => this.destroy());
}
createIframe(url) {
this.url = url;
this.iframe = document.createElement("iframe");
Object.assign(this.iframe.style, {
width: "1px",
height: "1px",
display: "none",
position: "absolute",
top: "0",
left: "0",
zIndex: "-1",
border: "none",
background: "transparent",
pointerEvents: "none",
opacity: "0",
visibility: "hidden"
});
this.iframe.src = url;
document.body.append(this.iframe);
return this.iframe;
}
postMessage(message) {
var _a;
if (this.iframe) {
(_a = this.iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage(message, this.url || "*");
}
}
onMessage(callback) {
window.addEventListener("message", (event) => {
if (typeof event.data.type !== "string") {
return;
}
callback(event.data);
});
}
removeMessageListener(callback) {
window.removeEventListener("message", callback);
}
destroy() {
var _a;
if (this.iframe) {
(_a = this.iframe) === null || _a === void 0 ? void 0 : _a.remove();
this.iframe = null;
}
}
}
export default IframeMessage;
//# sourceMappingURL=index.js.map