Modify page element as soon as it's loaded

喜欢而已 提交于 2019-12-13 09:49:43

问题


I'm currently writing a very simply Google Chrome Extension that utilizes Content Scripts, to simply add additional text onto a webpage by grabbing the element and appending to its innerHTML when the page is finished loading.

The issue is that the webpage I'm modifying is rich in media and takes several seconds to load, thus causing the additional text to not display until a few seconds after the rest of the text has loaded.

The element I'm grabbing is a span. Is there any way of listening for this element to be loaded so that I can modify it as soon as possible?


回答1:


As stated in the comments, inject your content script at "document_start" using the manifest setting "run_at"

Then use a MutationObserver on document to listen for it to be added.

Javascript

new MutationObserver(function (mutations) {
    mutations.some(function (mutation) {
        console.log(mutation);
        if (mutation.type === 'childList') {
            return Array.prototype.some.call(mutation.addedNodes, function (addedNode) {
                if (addedNode.id === 'added') {
                    mutation.target.textContent = 'Added text';
                    return true;
                }

                return false;
            });
        }

        return false;
    });
}).observe(document, {
    attributes: false,
    attributeOldValue: false,
    characterData: false,
    characterDataOldValue: false,
    childList: true,
    subtree: true
});

document.addEventListener('DOMContentLoaded', function onDOMContentLoaded() {
    var div = document.createElement('div');

    div.id = 'added'
    document.body.appendChild(div);
    console.log('Added a div');
}, true);

On jsFiddle



来源:https://stackoverflow.com/questions/24728162/modify-page-element-as-soon-as-its-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!