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

前端 未结 2 967
不知归路
不知归路 2020-12-18 15:43

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 resu

2条回答
  •  盖世英雄少女心
    2020-12-18 15:52

    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=).

    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);
    }
    

提交回复
热议问题