0

I am loading iframe source document.getElementById('iframeID').src = source here in function and that function is called again every second until my requirement is fulfilled.

When internet disconnected in between this process I get status cancelled in network panel and process continue when internet connected again (my requirement). so how can I catch this error and show error message to user.

I have already tried jQuery to assign src and catch error but that didn't work and affected my required functionality.

I also tried using try/catch but it didn't work.

John Conde
  • 217,595
  • 99
  • 455
  • 496

1 Answers1

0

You can capture load errors by adding an event listener to the tag. Here's an example doing the same for an image, using a URL that doesn't resolve.

const image = document.getElementById("img");
const invalidUrl = "https://localhost:1000/doesNotExist.png";
img.src = invalidUrl;

image.addEventListener("error", event => {
  console.log(`${event.type}: Loading image`);
});
<img id="img" />

I'd also recommend building in some functionality to suspend checking every second if you go offline, as @epascarello mentioned.

// resume automatic checks
window.addEventListener('online', () => console.log('Became online'));
// suspend automatic checks
window.addEventListener('offline', () => console.log('Became offline'));
GenericUser
  • 3,003
  • 1
  • 11
  • 17