问题
I'm currently writing a very simply Google Chrome Extension that utilizes Content Scripts, to simply add additional text onto a webpage by grabbing the element and appending to its innerHTML
when the page is finished loading.
The issue is that the webpage I'm modifying is rich in media and takes several seconds to load, thus causing the additional text to not display until a few seconds after the rest of the text has loaded.
The element I'm grabbing is a span
. Is there any way of listening for this element to be loaded so that I can modify it as soon as possible?
回答1:
As stated in the comments, inject your content script at "document_start" using the manifest setting "run_at"
Then use a MutationObserver on document
to listen for it to be added.
Javascript
new MutationObserver(function (mutations) {
mutations.some(function (mutation) {
console.log(mutation);
if (mutation.type === 'childList') {
return Array.prototype.some.call(mutation.addedNodes, function (addedNode) {
if (addedNode.id === 'added') {
mutation.target.textContent = 'Added text';
return true;
}
return false;
});
}
return false;
});
}).observe(document, {
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
childList: true,
subtree: true
});
document.addEventListener('DOMContentLoaded', function onDOMContentLoaded() {
var div = document.createElement('div');
div.id = 'added'
document.body.appendChild(div);
console.log('Added a div');
}, true);
On jsFiddle
来源:https://stackoverflow.com/questions/24728162/modify-page-element-as-soon-as-its-loaded