Search code examples
javascriptdomiframepeoplesoft

Access iframe elements after refresh


I am trying to extract data from a school peoplesoft portal page with an iframe element. On the Homepage, the page source has the iframe element. When I click on a button to leave that page(i.e. search classes) the page source stays the same but the elements on the page are different(observed using inspect element). I can access elements on the homepage, but not any of the others because I don't think I take into account the reloading of data/injection of other elements in the iframe. How can I access the elements post reload? this is the snippet i'm using to access elements:

var iframe = document.getElementById("id of iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var element = innerDoc.getElementById("name of id desired in iframe");

Solution

  • Thats because upon navigating, the document of the iframe changes, and your innerDoc variable stores the value of the old document, You can create a function in order to retrieve the document instead of storing it in a static variable:

    var iframe = document.getElementById("id of iframe");
    function getInnerDoc() {
        return iframe.contentDocument || iframe.contentWindow.document;
    };
    var element = getInnerDoc().getElementById("name of id desired in iframe");
    

    As per your comments, it seems that the whole iframe gets stored in the variable and never refreshes, you should create a function in order to get the iframe document each time you need to retrieve an element:

    function getIframeDocument(iframeId) {
        var iframe = document.getElementById(iframeId);
        return iframe.contentDocument || iframe.contentWindow.document;
    };
    var element = getIframeDocument().getElementById("name of id desired in iframe");