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?
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 });
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With