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
633 views
in Technique[技术] by (71.8m points)

dom - How to know when Google search results page renders its results?

I'm writing a Chrome extension that injects scripts to the Google's search result page and modified all the results' anchor elements.

My problem is that the results are rendered asynchronously and are not shown in the page on document load/ready.

I had 2 initial solutions which don't work:

  1. Set a timeout: Bad practice but it works. Nevertheless, might show inconsistent results so I prefer to avoid this solution.

  2. Bind to 'DOMNodeInserted'. Generally works, but more complicated in my case because I insert new nodes my self before the anchors, which triggers a recursion. I can insert code to avoid it if the anchor is already 'tagged', but again, this solution is bad since I need to traverse all the anchors each time a node is inserted - from what I checked this happens more than 140 times in the search result page.

Is there any kind of custom event Google trigger on the search results page? Is there any other DOM event that can work in this case?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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:

  1. The user enters a search term Enter
  2. The search results are updated.
  3. 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);
}

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

...