Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

jquery - Chrome-extension Javascript to detect dynamically-loaded content

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...