In general, you can use Mutation Observers to listen for document changes. To avoid recursion, simply disconnect the mutation observer before changing the document, then enable it again.
Conceptually, it is not much different from the DOMNodeInserted
event, so you can also remove the event listener, insert your nodes, then rebind the event listener. However, Mutation observers are more efficient, so you should use these instead of the DOM mutation events.
In this specific case (Google's search results), you can also use the hashchange
event to detect when Google has rendered new search results. This method is only useful because there's a correlation between the location fragment, the search terms and the search results:
- The user enters a search term Enter
- The search results are updated.
- The location fragment is changed (
https://www.google.com/search?q=old#q=<new term>
).
Example:
// On document load
printResult();
// Whenever the search term is changed
window.addEventListener('hashchange', function(event) {
printResult();
});
function printResult() {
// Example: Print first search result
console.log(document.querySelector('h3 a').href);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…