一旦它被加载,修改页面元素 [英] Modify page element as soon as it's loaded

查看:228
本文介绍了一旦它被加载,修改页面元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个非常简单的Google Chrome浏览器扩展程序,它利用内容脚本,通过抓取元素并附加到 innerHTML 时简单地将其他文本添加到网页上该页面已完成加载。

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.

我抓住的元素是 span 。有没有什么方法可以监听这个元素被加载,以便我可以尽快修改它?

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?

推荐答案

如上所述在评论中,使用清单设置run_at在document_start注入内容脚本

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

然后使用 c $> $ MutualObserver 文档上监听它。

Javascript

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);

jsFiddle

这篇关于一旦它被加载,修改页面元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆