Chrome扩展程序Javascript来检测动态加载的内容 [英] Chrome-extension Javascript to detect dynamically-loaded content
问题描述
我正在实施Chrome扩展程序。 我想用标签(在我的webapp的主页上)将href属性替换为#。问题是标签可能会被ajax动态加载,并且可能会被用户操作重新加载。有关如何让Chrome扩展检测ajax加载html内容的任何建议?
有两种方法可以做到这一点,第一种解决方案是处理ajax请求
有一个 .jquery中的ajaxComplete()函数,它可以处理页面上的所有ajax请求。
$ b
在内容脚本
,
var actualCode ='('+ function(){
$(document ).ajaxComplete(function(){
alert('内容刚刚改变,你应该再次改变href标签');
// chaging href标签代码将在这里
});
} +')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
第二种解决方案是监听内容变化
这可以通过突变事件来实现,同样在内容脚本
$(document).bind(DOMSubtreeModified,function(){
alert(页面上的内容已更改,应更新href标签);
});
您可以使用一些不同的选择器来限制您控制更改的元素。
$(body)。bind(DOMSubtreeModified,function(){}); //只监听对内容的更改
$(#mydiv)。bind(DOMSubtreeModified,function(){}); //只听取#mydiv内容的变化
I'm implementing a chrome extension app. I want to replace href attribute in tag (on my webapp's homepage) with "#". The problem is that the tag might be dynamically loaded by ajax, and could be reloaded by user actions. Any suggestions on how to let chrome-extension detect ajax loaded html content?
There are two ways to do it,
First solution is handling the ajax requests
There is a .ajaxComplete() function in jQuery which handles all ajax request on page.
In 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);
Second solution is listening the content changes
This is possible with mutation events, again in content script
$(document).bind("DOMSubtreeModified", function() {
alert("something has been changed on page, you should update href tag");
});
You might use some different selector to restrict the elements that you're controling the changes.
$("body").bind("DOMSubtreeModified", function() {}); // just listen changes on body content
$("#mydiv").bind("DOMSubtreeModified", function() {}); // just listen changes on #mydiv content
这篇关于Chrome扩展程序Javascript来检测动态加载的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!