Search code examples
javascriptjquerygoogle-chrome-extensionfirefox-addon

Browser Extension: How to execute a function when an element is loaded


I am working on a browser extension. It has two parts:

  1. popup - which contains checkboxes
  2. content script - which contains the code to alter the CSS property

I am saving the states of checkboxes so that the next time I open the popup again the same checkboxes are marked as checked. When I use the checkboxes they change the DOM as intended, however when I try to alter the DOM after the page is loaded, changes are not reflected. This is probably because the element on which I want to perform the operation is loaded slow and thus required operations fail.

I tried to use onload and ready but nothing worked

$('.question-list-table').on('load', function() {
    browser.storage.local.get(["options"], modifyThenApplyChanges)
});

I also tried, but nothing changed.

$('body').on('load','.question-list-table', function() {
    browser.storage.local.get(["options"], modifyThenApplyChanges)
});

Also, there is no visible error with the popup or content script as I test in both Google Chrome and Mozilla Firefox.

Update:

As suspected earlier, the target element is loaded slowly so I used setTimeout for 5 seconds and the script is working as intended.

Loading time is variable and I want to show my changes as early as possible everything in a consistent manner.


Solution

  • After going through MutationObserver as suggested by @charlietfl in the comment section, this is what I coded and works for me

    // Mutation Observer
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function(mutation) {
            if(mutation.addedNodes.length) {
               //do stuff
            }
        });
    });
    
    el = document.getElementsById('elementId');
    if(el) {
        observer.observe(el, {
            childList: true // specify the kind of change you are looking for
        });
    }