DEV Community

fbcyborg
fbcyborg

Posted on

Detecting ERR_CONNECTION_TIMED_OUT on IFrame load in React

Hello,

I started working on a React Component which contains an Iframe that should load and contain a web page.
Sometimes the web page is unreachable and I get the following error within the browser console:
ERR_CONNECTION_TIMED_OUT

I tried many solutions in React but unable to intercept such timeout error.

Here's what I have tried to do:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

export const ComponentFrame = (props) => {
  const [status, setStatus] = useState(null);

  const CHECK_INTERVAL = 1000;

  useEffect(() => {
    const iframe = document.getElementById('player');
    if(!iframe) {
      console.log('useEffect >> inside useEffect(): !iframe', 'DEBUG');
    }

    const startPolling = () => {
      console.log('startPolling >>', 'DEBUG');
      if (iframe.querySelector(`iframe[src="${props.iframeSrc}"`)) {
        console.log('startPolling >> iframe is ready', 'DEBUG');
        return;
      } else {
        console.log('startPolling >> iframe is not yet loaded!', 'DEBUG');
      }
      setTimeout(startPolling, CHECK_INTERVAL);
    };

    const handleIframeLoad = () => {
      try {
        startPolling();
      } catch (error) {
        console.log('handleIframeLoad >> ' + error, 'ERROR');
      }
    };

    const handleIframeError = (event) => {
      const errorMessage = event.message || 'Unknown error';
      console.log('handleIframeError >> errorMessage: ', errorMessage, 'ERROR');
      if (errorMessage.includes('ERR_CONNECTION_TIMED_OUT')) {
        console.log('handleIframeError >> Connection timed out in iframe:', errorMessage, 'ERROR');
      }
    };

    try {
      iframe.addEventListener('load', handleIframeLoad);
    } catch (error) {
      console.log('addEventListener >> ' + error, 'ERROR');
    }

    return () => {
      iframe.removeEventListener('load', handleIframeLoad);
      iframe.contentWindow.removeEventListener('error', handleIframeError);
    };
  }, []);

  return (
    <div className="external-content-wrapper">
      <iframe
        frameborder="0"
        sandbox="allow-scripts allow-same-origin allow-forms"
        id="player"
        src={props.iframeSrc}
        allowFullScreen={1}
        title="Remote page"
        width="100%"
        height="100%"
        onLoad={this.handleIframeLoad.bind(this)}
        onError={this.handleIframeError.bind(this)}
      />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Basically I would like to perform a new iframe content reload when ERR_CONNECTION_TIMED_OUT occurs.

Could you please help?

Top comments (0)