Получение сообщений о событиях с помощью postMessages не работает в компоненте реакции - PullRequest
0 голосов
/ 27 мая 2020
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<iframe width="600" height="800" id="game_frame" src="some-url"></iframe>
</body>
<script>
    var GameCommunicator = {
        source: undefined,
        targetOrigin: undefined,
        init: function (element) {
            window.addEventListener("message", this.processGameMessage.bind(this));
            this.source = element.contentWindow;
            this.targetOrigin = "*";
        },
        postMessage: function (data) {
            this.source.postMessage(data, this.targetOrigin);
        },

        processGameMessage: function (e) {
            if (e.data.type === 'backToLobby') {
                // here I want to get all actions with related to some type
            }
        }
    }
    document.getElementById("game_frame").onload = function() {
        GameCommunicator.init(document.getElementById("game_frame"));
        GameCommunicator.postMessage({ messageType: 'addEventListener', eventType: 'backToLobby'})
    }
</script>
</html>

Выше вы можете увидеть случай, когда я создаю простой файл index. html и пытаюсь взаимодействовать с iframe, и все работает хорошо, тогда я хочу реализовать то же самое с компонентом реакции


const Iframe = ({ gameUr }) => {
  const classes = useStyles()

  const ref = useRef()

  const { initializeListener } = useCrossWindowCommunication()

  useEffect(() => {
    const iframe = document.getElementById('game_frame')

    if (!ref.current && iframe) {
      ref.current = true

      if (iframe) {
        initializeListener(iframe)
      }
    }
  })

  return (
    <>
      <div className={classes.root} id="gameContainer">
          <iframe
            src={gameUrl}
            className={classes.gameFrame}
            id="game_frame"
          />
      </div>
    </>
  )
}

const useCrossWindowCommunication = () => {
  const initializeListener = function(iframe) {
    const instance = iframe.contentWindow

    if (instance) {
      instance.addEventListener('message', function(event) {
        console.log(event.data, 'event')
      })

      instance.postMessage(
        {
          messageType: 'addEventListener',
          eventType: 'backToLobby'
        },
        '*'
      )
    }
  }

  return {
    initializeListener
  }
}

В случае с компонентом перехвата и реагирования он не работает, но, как вы можете видеть, код делает то же самое в первом и втором случае, что я делаю не так?

...