Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute content script after the page is loaded completely

I'm trying to write a Google chrome extension that grabs the element in the page by its class name. The idea is to use the content script to grab these elements and pass the messages to the extensions and pop up. However, my content script always end up executing before the entire page is loaded so I can't grab the elements that I want. I try using window.loaded and document.loaded but it didn't work. I also tried wait an interval but the script always ended up executing at the exact same stop point.

// my content script

if (document.readyState == "complete"){
    var board_name_arr = [];
    var node = document.getElementsByClassName('Board');

    for (var i = 0; i < node.length; ++i){
        var board_name = node[i].getElementsByClassName('boardName')[0].textContent;
        board_name_arr[i] = board_name;
    }

    if (Object.keys(board_name_arr).length){
        alert("found board");
    }
}

Is there a way to force it to run after ? Or should I not be using content script approach?

like image 587
Irene Yeh Avatar asked Jan 28 '15 21:01

Irene Yeh


2 Answers

Probably the page loads its content dynamically though AJAX, so the elements you want to find may be still not loaded when the document state is ready. Even if some part of content is loaded on start, more content may come later. To solve this issue correctly I'd recommend you the MutationObserver techniques. I used it in my Chrome extension to inject the 'Favorite' button to each Facebook post and it worked perfectly.

See the code sample:

var obs = new MutationObserver(function (mutations, observer) {
    for (var i = 0; i < mutations[0].addedNodes.length; i++) {
        if (mutations[0].addedNodes[i].nodeType == 1) {
            $(mutations[0].addedNodes[i]).find(".userContentWrapper").each(function () {
                injectFBMButton($(this));
            });
        }
    }
    injectMainButton();
});
obs.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false });
like image 125
Alexander Dayan Avatar answered Oct 18 '22 21:10

Alexander Dayan


Without jQuery you can do this defining a callback function on the page load event. You can do it this way :

var loadfunction = window.onload;
window.onload = function(event){
    //enter here the action you want to do once loaded

    if(loadfunction) loadfunction(event);
}

Or this way :

window.addEventListener("load", function load(event){
    window.removeEventListener("load", load, false); //remove listener, no longer needed
    //enter here the action you want to do once loaded 
},false);
like image 24
NeoPix Avatar answered Oct 18 '22 20:10

NeoPix