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 aj
Solution 1:
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
Solution 2:
The accepted answer is outdated. As of now, 2019, Mutation events are deprecated. People should use MutationObserver. Here is how to use it in pure javascript:
// Select the node that will be observed for mutationsvar 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 observedvar callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
elseif (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback functionvar observer = newMutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
Post a Comment for "Chrome-extension Javascript To Detect Dynamically-loaded Content"