亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用window.postmessage與父窗口通信

如何使用window.postmessage與父窗口通信

烙印99 2022-12-22 11:57:23
我正在創建一個反應應用程序,我希望我的用戶將其嵌入到他們的網站上。此應用程序將顯示在兩個 iframe 中,但我想一次只顯示一個 iframe。因此,該應用程序的一部分是一個簡單的按鈕,第二部分是一個表單,一旦用戶決定使用該應用程序(它是一個聊天應用程序)就會彈出。我設置了一個非常簡單的組件來顯示按鈕,以便它可以向父網站發送消息。我不確定自己做錯了什么,但是發送 window.postmessage 事件時,出現錯誤:Uncaught DOMException: Blocked a frame with origin "http://localhost:3002" from accessing a cross-origin frame.這是示例父網站代碼:<h1>Hello! This is some static content</h1>    <iframe src="http://localhost:3002"        style="width: 108px; height: 50px; padding: 0px; margin: 10px 20px; position: fixed; bottom: 0px; right: 0px; overflow: visible; opacity: 1; border: 0px; z-index: 999998; transition-duration: 250ms; transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1); transition-property: opacity, top, bottom;"        id="dbhchat"></iframe>    <h3>Thanks for checking out my blog!</h3>    <script>        window.addEventListener('message', event => {            // IMPORTANT: check the origin of the data!             if (event.origin.startsWith('http://localhost:3002')) {                // The data was sent from your site.                // Data sent with postMessage is stored in event.data:                console.log(event.data);            } else {                // The data was NOT sent from your site!                 // Be careful! Do not use it. This else branch is                // here just for clarity, you usually shouldn't need it.                return;            }        });    </script>以及將消息發送到父窗口的組件:import React from 'react';import { IconButton } from '@material-ui/core';import PhotoCamera from '@material-ui/icons/PhotoCamera';import './App.css';function App() {  const send = () => {    if (window && window.parent) {      console.log('we have message sending here', window.parent);      window.parent.postMessage('message', 'http://localhost:3002', false);    }  }在此先感謝您提供幫助解決這個問題!
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

我發現了一個有點古怪的解決問題的方法。我真的不知道為什么會這樣,但之后簡單地添加e.preventDefault()到 react 發送函數就可以正常工作了。


const send = (e) => {

    e.preventDefault();

    if (window && window.parent) {

      window.parent.postMessage({message: 'The message is being set up here', hide: 'dbhchat', show: 'dbhchat'}, '*');

    }

}

添加之后,一切正常。如果有人可以提供更多詳細信息,說明為什么會這樣,那就太好了!


查看完整回答
反對 回復 2022-12-22
  • 1 回答
  • 0 關注
  • 300 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號