Search code examples
javascriptdomgoogle-chrome-extension

How to update a webpage title that after the page has loaded and while the DOM updates dynamically?


I'm attempting to create my first google chrome extension that updates the title of a specific website's webpage. My extension retrieves an element from the webpage that has a part number (partNum) and I want to update the title of the page to be this part number.

So far, I've only been able to get the title to update once the page has initially loaded. The webpage has various tabs and buttons that get pressed when in use (too many to listen to) that may or may not change the url but for some reason they overwrite the title to the original useless title. I'm looking for how to update the title for each time the DOM gets shuffled around or the url updates. Ideally, I would like to keep the title I assign on page load until the url changes but I haven't been able to find which event is updating the title to stop or trigger my own change on.

I'm trying to avoid using a timer approach for updating the page every few seconds because that's probably the wrong way to go about it.

Below is my current javascript file and manifest file for the extension. The popup isn't really needed because I want this script to run as long as the extension is enabled.

titleChanger.js

window.onload = function() {
    partNum = document.getElementById("frmSubTitleMenu_lblMainMenu_Text").textContent
    document.title = partNum
}

manifest.json

{
    "manifest_version": 2,

    "name": "Tab Title Changer",
    "description": "Renames the title of the browser tab to be a part number",
    "version": "1.0",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

    "content_scripts": [ {
        "matches": ["http://www.website.com/*"],
        "js": ["titleChanger.js"]
    } ]
}

Thank you


Solution

  • Managed to get a working solution using the snippet below. Ran into an infinite loop before I added the prevTitle check since it detected its own change and got caught.

    // Create an observer on the title element
    let observer = new MutationObserver(updateTitle);
    observerOptions = {childList: true};
    observer.observe($('head > title')[0], observerOptions);
    
    // Update the title of the WebPage if there is a change
    function updateTitle () {    
        newTitle = $(newTitleID)[0].innerText;
    
        // Changes the title if it is different from the previous Mutation
        if ($('head > title')[0].innerText != prevTitle) {
            document.title = newTitle;
            prevTitle = newTitle;
        }        
    };