Я создаю приложение для реагирования, которое хочу, чтобы мои пользователи встраивали на свои веб-сайты. Это приложение будет отображаться в двух окнах 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);
}
}
return (
<div className="App">
<header style={{ background: 'red' }} className="App-header">
<IconButton onClick={send} color="primary" aria-label="upload picture" component="span">
<PhotoCamera />
</IconButton>
</header>
</div>
);
}
export default App;
Заранее благодарим за любую помощь в выяснении этого вопроса!