How to get full loaded HTML source from web site in a Chrome Extension

I need the same source i can find in the Elements window of DevTool console in my extension. I tried using the content script

var text = document.documentElement.innerHTML;

injected after catched the “complete” status from chrome.tabs.onUpdated.addListener, but i recived only the html code without the content dynamically created.

In particular i want my extension to find all “div” added dynamically.

Any help will be appreciated!

Answer

The complete event fires once the initial page content has been loaded. It has no relation to dynamically generated content, otherwise it would have to wait indefinitely, since more content may always be added later.

If you are interested in a specific element, you can use setTimeout to periodically poll for the element. Like so:

function getElement() {
    return new Promise(function(res, rej) {
        var interval = setInterval(function() {
            var elm = document.getElementById('the-element-you-want');
            if(elm){
                clearInterval(interval);
                res(elm);
            }
        }, 10);
    });
}

Another option would be to use a MutationObserver to detect when the desired element(s) have been created.

Leave a Reply

Your email address will not be published. Required fields are marked *