Chrome扩展程序Javascript可检测动态加载的内容

Kev*_*ang 7 javascript jquery google-chrome-extension

我正在实施Chrome扩展应用.我想用标签(在我的webapp的主页上)用"#"替换href属性.问题是标记可能由ajax动态加载,并且可以由用户操作重新加载.关于如何让chrome-extension检测ajax加载的html内容的任何建议?

oca*_*nal 18

有两种方法可以做到,

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

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

content script,

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);
Run Code Online (Sandbox Code Playgroud)

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

对于突变事件,这也是可能的content script

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

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

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

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


r.m*_*nov 5

接受的答案已过时。截至 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();
Run Code Online (Sandbox Code Playgroud)