首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Chrome扩展Javascript以检测动态加载的内容

Chrome扩展Javascript以检测动态加载的内容
EN

Stack Overflow用户
提问于 2013-08-01 05:43:09
回答 2查看 7.9K关注 0票数 8

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-02 12:43:48

有两种方法,

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

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

content script中,

代码语言:javascript
复制
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中也是如此。

代码语言:javascript
复制
$(document).bind("DOMSubtreeModified", function() {
    alert("something has been changed on page, you should update href tag");
});

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

代码语言:javascript
复制
$("body").bind("DOMSubtreeModified", function() {}); // just listen changes on body content

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

Stack Overflow用户

发布于 2019-07-07 20:22:49

接受的答案已经过时了。截至目前,2019年,突变事件已不再受欢迎。人们应该使用MutationObserver。下面是如何在纯javascript中使用它:

代码语言: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();
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17986020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档