1

I had problem with iframe that was loading a document using google document viewer, sometimes the document would not load.

I used this solution to check if iframe is successfully loaded, or if it should be reloaded.

The solution works great on pc(chrome), but on iphone(safari) $('#iframe').on('load', ...) event triggers even when there is no content.

On pc on load event is only triggered when iframe is trully loaded and has content.

 function reloadIFrame() {
    document.getElementById("ifm").src=document.getElementById("ifm").src;
 }
 ints.push( setInterval("reloadIFrame();", 2000));

  $( document ).ready(function() {
      $('#ifm').on('load', function() {
          // this event fires even when there is no content on safari
          // ....stop reloading the iframe etc.....
          alert($('#ifm').attr('src')); // this gives me correct url, even when not loaded

Iframe:

<iframe data-iframe="true" id="ifm" data-ext="<?php echo $ext ?>" 
  class="document-iframe"  
  src="<?php echo $full_src ?>" data-tool-id="<?php echo $tool->ID ?>">
 </iframe>
failedCoder
  • 1,346
  • 1
  • 14
  • 38
  • @Lain I've added alert($('#ifm').attr('src')); to on load, and I get the proper url, even when it doesnt load – failedCoder Dec 02 '19 at 14:35
  • The `src` attribute is kinda static, so not very reliable. The window.location.href on the iframe shows you the actual site. Does the site (=src) exist and have content? How do you define content? – Lain Dec 02 '19 at 14:44
  • @Lain I've added the iframe html to my question, iframe src definitely exists, the problem is that google document reader fails every so often so I have to check if iframe is loaded successfully. – failedCoder Dec 02 '19 at 14:58
  • Well, then it seems correct to me that Safari triggers `onload`. Also be aware that Chrome does not trigger the event on download links. – Lain Dec 02 '19 at 15:08

2 Answers2

2

If relevant to anyone, resolved the Safari issue using the iframe element contentWindow.length. you can get more info here: HTMLIframeElement

When on Safari the onLoad is activated in any case so the onLoad function makes sure content was actually loaded or needs to reload

This is my solution based on the original solution posted here

iframeLoaded() {
 const contentLoaded = this.refs.iframe.contentWindow.length

 if (!!contentLoaded) {
   clearInterval(this.iframeTimeoutId)
 }
 else {
   this.updateIframeSrc()
 }
}
Shimrit Snapir
  • 433
  • 3
  • 7
0

I failed to make this work properly, so I switched to pdf.js viewer instead of google document viewer. Its missing some minor features that google document viewer has, but at least it works properly every time.

<iframe height='100%' class="document-iframe" width='100%' scrolling='no' 
  allowfullscreen webkitallowfullscreen src='<?php echo get_template_directory_uri() 
?>/web/viewer.html?file=<?php echo $src ?>'>
</iframe> 
failedCoder
  • 1,346
  • 1
  • 14
  • 38