Search code examples
javascripthtmlpdfiframeappendchild

Iframe doen't load content after src changed | Javascript


I am currently writing a website that is supposed to run on an info terminal.
It has an <iframe> showing the content selected from a menu.

The menu contains PDFs and a Schedule for the employees.
The PDF reader and the Schedule are both on separate HTML documents.
They both work perfectly, but !

My problem occurs when I change the documents src inside the frame.

var iframe = document.getElementById('iframe');
iframe.src = src_clicked;

I am using pdf.js to render the PDFs. I render each page on a <canvas> and append them all to a <div>. When I start the page with a PDF, everything works! But when my iframe has had a different src before, it wont append the rendered pages to my container again.

I tried reloading the page inside the iframe like this. But it doesn't do anything.

var ifrm = document.getElementById("iframe");
var iframeDoc = ifrm.contentWindow.document;
ifrm.contentWindow.location.reload(true);


This is how i render the PDF with pdf.js:

PDFJS.getDocument(pageUrl).then(function(pdf) {
        var currentPage = 1;
        var pages = [];
        pdf.getPage(currentPage).then(renderPage);
        function renderPage(page) {
            var canvas = document.createElement('canvas');
            ... //define renderContext
            var renderContext = { ... };
            page.render(renderContext).then(function () {
                if(currentPage < pdf.numPages + 1) {
                    pages[currentPage-1] = canvas;
                    pdf.getPage(currentPage++).then(renderPage);
                }
            });
        }
    });


I don't have any idea what Im doing wrong here.
Please help me


Solution

  • I just solved it this way:

    When displaying a PDF, I remove the iFrame:

    document.getElementById('container').innerHTML = "";
    
    loadPDF(pdfPath);
    

    and append the document right onto the <div>


    When I display a web content again, I append a new iFrame:

    document.getElementById('container').innerHTML =
             '<iframe id="iframe" type="text/html" src="' + websiteURL + '" ></iframe>';
    

    And give it the full size:

    #iframe{
        width:  100%;
        height: 100%;
        display:block;
    }