update iframe.helper.js

This commit is contained in:
Harvey committed 2022-10-20 17:19:02 +08:00
1 parent d055eb3e60
commit 96781698ba
2 files changed
+66 -12

No files matched your search

+30 -11
View File
@@ -1,5 +1,5 @@
class IframeHelper {
static postMessage(type, data, id = 0) {
static postMessage({ type, data, id = 0 }) {
window.parent.postMessage(
{
type: type,
@@ -18,12 +18,17 @@ class IframeHelper {
if (data.match(/resolve\((.*?)\)/)) {
const string = `return new Promise(function(resolve){\n${data}\n})`;
const result = await new Function(string)();
IframeHelper.postMessage('response', result, id);
IframeHelper.postMessage({ type: 'response', data: result, id });
} else {
IframeHelper.postMessage('response', new Function(data)(), id);
IframeHelper.postMessage({ type: 'response', data: new Function(data)(), id });
}
} catch (error) {
IframeHelper.postMessage('error', error.message, id);
IframeHelper.postMessage({ type: 'error', data: error.message, id });
}
break;
case 'destroy':
if (!IframeHelper.isDestroy) {
IframeHelper.destroy();
}
break;
default:
@@ -32,11 +37,16 @@ class IframeHelper {
}
static inject() {
IframeHelper.postMessage('inject');
IframeHelper.isInject = true;
IframeHelper.isDestroy = false;
IframeHelper.postMessage({ type: 'inject' });
window.addEventListener('message', IframeHelper.onMessage);
}
static destroy() {
IframeHelper.isInject = false;
IframeHelper.isDestroy = true;
IframeHelper.postMessage({ type: 'destroy' });
window.removeEventListener('message', IframeHelper.onMessage);
}
@@ -45,6 +55,7 @@ class IframeHelper {
this.isInject = false;
this.isDestroy = false;
this.$iframe = iframe;
this.messageCallback = null;
this.onMessage = this.onMessage.bind(this);
window.addEventListener('message', this.onMessage);
this.$iframe.src = url;
@@ -59,6 +70,9 @@ class IframeHelper {
break;
case 'destroy':
this.isInject = false;
if (!this.isDestroy) {
this.destroy();
}
break;
default:
break;
@@ -70,12 +84,15 @@ class IframeHelper {
} else {
this.promises[id].resove(data);
}
delete this.promises[id];
}
if (this.messageCallback) {
this.messageCallback({ type, data });
}
}
postMessage(type, data) {
postMessage({ type, data }) {
return new Promise((resove, reject) => {
(function loop() {
if (this.isInject) {
@@ -100,10 +117,12 @@ class IframeHelper {
commit(callback) {
const callbackString = callback.toString();
const bodyString = callbackString
.substring(callbackString.indexOf('{') + 1, callbackString.lastIndexOf('}'))
.trim();
return this.postMessage('commit', bodyString);
const bodyString = callbackString.substring(callbackString.indexOf('{') + 1, callbackString.lastIndexOf('}'));
return this.postMessage({ type: 'commit', data: bodyString });
}
message(callback) {
this.messageCallback = callback;
}
destroy() {