Home > Net >  Hiding DOM elements with a chrome extension without causing a flicker
Hiding DOM elements with a chrome extension without causing a flicker

Time:05-06

Preface:

I am aware that there is a duplicate question out there. I am posting it again because it has no answers (and it's from 4 years ago).

General description of what I want:

I want to be able to hide a DOM-element (adding Element.style.display = "none") before the DOM is loaded into the view.

What I've tried:

Other posts point to using a MutationObserver and running it on the document element.

To ensure that we are able to hide an element before the DOM is loaded, we are to run the script containing the MutationObserver as a content_script with "run_at":"document_start".

I did all of this, and I still see a flicker (the elements appear when I load a page and then quickly disappear).

What I'm trying to do:

There's a ul which contains some li with some text on the page I inject my content_script.js into. I populate my popup.html with <text, checkbox> pairs. If the checkbox is checked, the li containing said text is visible, else it is hidden. I want it to persist between refreshes, hence the use of storage.

Things work - but there's a flicker whenever I refresh the page. The elements are there, then they're gone. I don't want them to show up in the first place!

My code:

When I detect that the DOM elements I may remove have loaded, I generate an Object that indicates whether I should hide or keep visible that specific DOM element. I then set its Element.style.display to none or block accordingly.

/**manifest.json
...
"content_scripts": [
    {
      "matches": [
        "some_website_url"
      ],
      "js": [
        "content_script.js"
      ],
      "run_at": "document_start"
    }
  ]
...
*/

///content_script.js
const mutationObserver = new MutationObserver((mutations) => {
    for (const { addedNodes } of mutations) {
        for (const node of addedNodes) {
            if (node.tagName) {
                if (node.querySelector(potentially_hidden_element_selector)) {
                    chrome.storage.sync.get("courses", ({ courses }) => {
                        chrome.storage.sync.set({ "courses": generateCourseList(courses) }, () => {
                            const courseElements = Array.from(node.closest('ul').querySelectorAll('a[data-parent-key="mycourses"]'))
                            courseElements.forEach(courseElement => {
                                const courseName = getCourseName(courseElement)
                                const isVisible = courses[courseName]
                                updateCourseElementInSidebar(courseElement, isVisible)
                            })
                        })
                    })
                    // We found what we were looking for so stop searching
                    mutationObserver.disconnect()
                }
            }
        }
    }
})

mutationObserver.observe(document, { childList: true, subtree: true })

EDIT 1:

My generateCourseList method depends on the DOM elements I may try to hide - so I can't call the chrome.storage.set method before the DOM has loaded I think.

When I refresh the page, a list of courses eventually populates the DOM. I then populate the storage's courses object based on these course elements' innerText properties. I set each of these elements' visibility to true or false based on one of two factors: if this course is already defined in the courses object, keep its visibility status, if it isn't, set it to true (visible by default).

I can't make certain DOM elements visible/hidden if I don't have reference to them though. So if I try to call generateCourseList before those specific DOM elements have loaded, I end up trying to retrieve all the course elements (document.querySelectorAll('a[data-parent-key="mycourses"]')) and get returned nothing. I end up setting courses in chrome.storage to nothing because of this chrome.storage.sync.set({ "courses": generateCourseList(courses) }....

EDIT 2:

Here is all of my code. I try to chrome.storage.sync.get as soon as I can, and I try to not depend on the result of chrome.storage.sync.set.

I try to delete the elements as soon as I can, but I'm having difficulty doing so. This is because I have difficulty knowing when the content I want to access (the course elements) have fully loaded. Previously, I was detecting when one course element was visible, and when it was, I assumed all were. This was a mistake. I was able to access the one courselement the moment it popped up, but sometimes only 4 of the 6 course elements were actually loaded. I can't hardcode this number, because it changes from person to person. I can't just tackle them one by one, because then I wouldn't know when to disconnect the MutationObserver. I used the debugger and tried to find what element is loaded soon after all 6 course elements are loaded, and that is the header#page-header.row element. I still get a flicker, though less noticeable than before.

Anything I can do to make it even less noticeable?

function start_mutation_observer() {
    chrome.storage.sync.get({ 'savedCourses': {} }, ({ savedCourses }) => {
        const observer = new MutationObserver((mutations) => {
            for (const { addedNodes } of mutations) {
                for (const node of addedNodes) {
                    // The page header gets updated AFTER the courseList is updated - so once it's in the page, we know the courseElements are too
                    if (document.querySelector('header#page-header.row')) {
                        observer.disconnect()

                        const generatedCourses = generateCourseList(savedCourses)
                        const courseElements = getCourseElements()

                        // Set visibility of course elements 
                        courseElements.forEach(courseElement => {
                            const courseName = getCourseElementTextContent(courseElement);
                            const isShown = generatedCourses[courseName];
                            setCourseElementVisibility(courseElement, isShown);
                        });

                        chrome.storage.sync.set({ 'savedCourses': generatedCourses });
                        return
                    }
                }
            }
        });
        observer.observe(document, { childList: true, subtree: true });

        // In case the content script has been injected when some of the DOM has already loaded
        onMutation([{ addedNodes: [document.documentElement] }]);
    });
}

function getCourseElements() {
    const COURSE_ELEMENT_SELECTOR = 'ul > li > a[data-parent-key="mycourses"]'
    return Array.from(document.querySelectorAll(COURSE_ELEMENT_SELECTOR))
}

function getCourseElementTextContent(courseElement) {
    const COURSE_ELEMENT_TEXT_CONTAINER_SELECTOR = 'a[data-parent-key="mycourses"] > div > div > span.media-body'
    return courseElement.querySelector(COURSE_ELEMENT_TEXT_CONTAINER_SELECTOR).textContent
}

function generateCourseList(savedCourses) {
    // Turns [[a, b], [b,c]] into {a:b, b:c}
    return Object.fromEntries(getCourseElements().map(courseElement => {
        const courseName = getCourseElementTextContent(courseElement)
        const isShown = savedCourses[courseName] ?? true
        return [courseName, isShown]
    }))
}

function setCourseElementVisibility(courseElement, isShown) {
    if (isShown) {
        courseElement.style.display = "block"
    } else {
        courseElement.style.display = "none"
    }
}

start_mutation_observer()

EDIT 3:

I think it's as good as can be now. I only refresh the visibility of the course elements that were just loaded into the DOM. There's essentially no flicker now (there is a slight one, but its' the same amount of flickering without my extension).

Here is the code for the MutationObserver

function start_mutation_observer() {
    let handledCourseElements = new Set()
    chrome.storage.sync.get({ 'savedCourses': {} }, ({ savedCourses }) => {
        const observer = new MutationObserver((mutations) => {
            for (const { addedNodes } of mutations) {
                for (const node of addedNodes) {
                    const courseElements = getCourseElements()
                    const courseElementsAdded = courseElements.length > handledCourseElements.size
                    // If a courseElement was added, update visibility of those that weren't already processed 
                    if (courseElementsAdded) {
                        const generatedCourses = generateCourseList(savedCourses)
                        courseElements
                            .filter(courseElement => !handledCourseElements.has(courseElement))
                            .forEach(courseElement => {
                                const courseName = getCourseElementTextContent(courseElement)
                                const courseShouldBeVisible = generatedCourses[courseName];
                                setCourseElementVisibility(courseElement, courseShouldBeVisible);
                                handledCourseElements.add(courseElement)
                            })
                    }

                    // The page header gets updated AFTER the courseList is updated - so once it's in the page, we know the courseElements are too
                    if (document.querySelector('header#page-header.row')) {
                        observer.disconnect()
                        chrome.storage.sync.set({ 'savedCourses': generateCourseList(savedCourses) });
                        return
                    }
                }
            }
        });
        observer.observe(document, { childList: true, subtree: true });

        // In case the content script has been injected when some of the DOM has already loaded
        onMutation([{ addedNodes: [document.documentElement] }]);
    });
}

CodePudding user response:

Reading storage is slow and asynchronous, so you need to do it at the beginning:

chrome.storage.sync.get('courses', ({ courses }) => {
  chrome.storage.sync.set({ 'courses': generateCourseList(courses) });
  const observer = new MutationObserver(onMutation);
  observer.observe(document, { childList: true, subtree: true });
  onMutation([{addedNodes: [document.documentElement]}]);
  function onMutation(mutations) {
    for (const { addedNodes } of mutations) {
      for (const node of addedNodes) {
        if (node.tagName && node.querySelector(potentially_hidden_element_selector)) {
          observer.disconnect();
          processNode(node, courses);
        }
      }
    }
  }
});

function processNode(node, courses) {
  const courseElements = Array.from(
    node.closest('ul').querySelectorAll('a[data-parent-key="mycourses"]'));
  courseElements.forEach(courseElement => {
    const courseName = getCourseName(courseElement);
    const isVisible = courses[courseName];
    updateCourseElementInSidebar(courseElement, isVisible);
  });
}
  • Related