feat: iframe expose postmessage function (#3368)

* feat: iframe postmessage

iframe postmessage

* chore: prettier format code

---------

Co-authored-by: invalid w <wangjuesix@gmail.com>
This commit is contained in:
luocong2016 2023-12-01 18:00:08 +08:00 committed by GitHub
parent cd71e60dd1
commit 05bc4acb9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -12,13 +12,14 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { CSSProperties } from 'vue'; import type { CSSProperties } from 'vue';
import { ref, unref, computed } from 'vue'; import { ref, unref, computed, onMounted, onUnmounted } from 'vue';
import { Spin } from 'ant-design-vue'; import { Spin } from 'ant-design-vue';
import { useWindowSizeFn } from '@vben/hooks'; import { useWindowSizeFn } from '@vben/hooks';
import { propTypes } from '@/utils/propTypes'; import { propTypes } from '@/utils/propTypes';
import { useDesign } from '@/hooks/web/useDesign'; import { useDesign } from '@/hooks/web/useDesign';
import { useLayoutHeight } from '@/layouts/default/content/useContentViewHeight'; import { useLayoutHeight } from '@/layouts/default/content/useContentViewHeight';
const emit = defineEmits(['message']);
defineProps({ defineProps({
frameSrc: propTypes.string.def(''), frameSrc: propTypes.string.def(''),
}); });
@ -54,6 +55,34 @@
loading.value = false; loading.value = false;
calcHeight(); calcHeight();
} }
const messageHandler = (e: MessageEvent) => {
emit('message', e.data);
};
const postMessage = (message: any, tragetOrigin: string, transfer?: Transferable[]) => {
const iframe = unref(frameRef);
if (!iframe) return;
iframe.contentWindow?.postMessage(message, tragetOrigin, transfer);
};
const reload = () => {
loading.value = true;
const iframe = frameRef.value;
if (!iframe) return;
iframe.contentWindow?.location.reload();
loading.value = false;
};
onMounted(() => {
window.addEventListener('message', messageHandler);
});
onUnmounted(() => {
window.removeEventListener('message', messageHandler);
});
defineExpose({ postMessage, reload });
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
@prefix-cls: ~'@{namespace}-iframe-page'; @prefix-cls: ~'@{namespace}-iframe-page';