Chrome扩展程序JavaScript检测动态加载内容

8

1
相关:是否有jQuery DOM更改监听器?(虽然我可能不会说是重复的,但你在这里的目标比那个问题要具体得多。) - apsillers
2个回答

18

有两种方法可以做到这一点,

第一种解决方案是处理ajax请求

jQuery中有一个.ajaxComplete()函数来处理页面上的所有ajax请求。

内容脚本中,

var actualCode = '(' + function() {
    $(document).ajaxComplete(function() { 
      alert('content has just been changed, you should change href tag again');
      // chaging href tag code will be here      
    });
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

第二种解决方案是监听内容变化

这可以通过使用 mutation eventscontent script 中实现。

$(document).bind("DOMSubtreeModified", function() {
    alert("something has been changed on page, you should update href tag");
});

你可以使用一些不同的选择器来限制你要控制更改的元素。

$("body").bind("DOMSubtreeModified", function() {}); // just listen changes on body content

$("#mydiv").bind("DOMSubtreeModified", function() {}); // just listen changes on #mydiv content

为什么要执行 script.parentNode.removeChild(script); ?这样做不会移除渲染页面上的所有现有脚本吗? - LondonAppDev
我认为这只是一个清理步骤。脚本仍然存在。虽然您无法使用断点进行调试,但“debugger”仍然会被触发。 - vothaison
这很棒 ocanal :) - Sumeet Gavhale

4

接受的答案已经过时。截至2019年,Mutation事件已被弃用。人们应该使用 MutationObserver 。以下是纯javascript如何使用它:

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

太好了!这正是我今晚在寻找的。顺便说一下,这里是config变量的所有选项 - Robert Lin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接