如何在页面加载后更新 DOM 动态更新的网页标题?

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

我正在尝试创建我的第一个 google chrome 扩展程序来更新特定网站网页的标题。我的扩展程序从具有部件号 (partNum) 的网页中检索一个元素,我想将页面标题更新为该部件号。

到目前为止,我只能在页面初始加载后更新标题。该网页有各种选项卡和按钮,在使用时会被按下(太多而无法收听),可能会或可能不会更改 url 但由于某种原因,它们会将标题覆盖为原始无用的标题。我正在寻找每次 DOM 随机播放或 url 更新时如何更新标题。理想情况下,我想保留我在页面加载时分配的标题,直到 url 更改,但我无法找到哪个事件正在更新标题以停止或触发我自己的更改。

我试图避免使用计时器方法每隔几秒更新一次页面,因为这可能是错误的做法。

下面是我当前的 javascript 扩展文件和清单文件。弹出窗口并不是真正需要的,因为只要启用了扩展程序,我就希望此脚本 运行。

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"]
    } ]
}

谢谢

使用下面的代码片段设法获得了一个可行的解决方案。 运行 在我添加 prevTitle 检查之前进入无限循环,因为它检测到自己的更改并被捕获。

// 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;
    }        
};