8

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

4

2 回答 2

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

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

这在突变事件中是可能的,同样在content 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
于 2013-08-02T12:43:48.040 回答
4

接受的答案已过时。截至目前,2019 年,突变事件已被弃用。人们应该使用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();
于 2019-07-07T20:22:49.817 回答