vue 内嵌外部页面

  1. 参考:https://blog.csdn.net/weixin_43957384/article/details/131111544

Plan

  1. Embed an HTML page in Vue:

    • Use an iframe to embed the external HTML page within a Vue component.
  2. Communicate between Vue and the embedded HTML page:

    • Use postMessage API for communication between the parent Vue component and the embedded HTML page.

Vue Component

  1. Create a Vue component that includes an iframe to embed the external HTML page.
  2. Set up event listeners to handle messages from the embedded HTML page.
  3. Use postMessage to send messages to the embedded HTML page.

Embedded HTML Page

  1. Set up event listeners to handle messages from the parent Vue component.
  2. Use postMessage to send messages to the parent Vue component.

Code

Vue Component (MyComponent.vue)

<template>
  <div>
    <iframe ref="iframe" src="path/to/embedded.html" @load="onIframeLoad"></iframe>
  </div>
</template>

<script>
export default {
  methods: {
    onIframeLoad() {
      const iframe = this.$refs.iframe.contentWindow;

      // Listen for messages from the embedded HTML page
      window.addEventListener('message', this.handleMessageFromIframe);

      // Send a message to the embedded HTML page
      iframe.postMessage({ type: 'INIT', data: 'Hello from Vue' }, '*');
    },
    handleMessageFromIframe(event) {
      if (event.origin !== 'expected-origin') return; // Validate the origin
      const { type, data } = event.data;

      if (type === 'RESPONSE') {
        console.log('Message from iframe:', data);
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleMessageFromIframe);
  },
};
</script>

Embedded HTML Page (embedded.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Embedded Page</title>
</head>
<body>
  <script>
    // Listen for messages from the parent Vue component
    window.addEventListener('message', function(event) {
      if (event.origin !== 'expected-origin') return; // Validate the origin
      const { type, data } = event.data;

      if (type === 'INIT') {
        console.log('Message from parent:', data);

        // Send a response back to the parent Vue component
        event.source.postMessage({ type: 'RESPONSE', data: 'Hello from embedded page' }, event.origin);
      }
    });
  </script>
</body>
</html>

Summary

  • Use an iframe to embed the HTML page in the Vue component.
  • Use postMessage API for communication between the parent Vue component and the embedded HTML page.
  • Ensure to validate the origin of messages for security.

posted on 2024-08-21 13:55  朝朝暮Mu  阅读(72)  评论(0)    收藏  举报