Chrome extension detect Google search refresh

前端 未结 1 1236
后悔当初
后悔当初 2020-12-22 02:56

How can my content script detect a refresh of Google\'s search? I believe it is an AJAX reload of the page and not a \"real\" refresh, so my events won\'t detect the refresh

相关标签:
1条回答
  • 2020-12-22 03:27

    Google search is a dynamically updated page. Several well-known methods exist to detect an update: MutationObserver, timer-based approach (see waitForKeyElements wrapper), and an event used by the site like pjax:end on GitHub.

    Luckily, Google Search in Chrome browser uses message event, so here's our content script:

    window.addEventListener('message', function onMessage(e) {
        // console.log(e);
        if (typeof e.data === 'object' && e.data.type === 'sr') {
            onSearchUpdated();
        }
    });
    
    function onSearchUpdated() {
        document.getElementById('resultStats').style.backgroundColor = 'yellow';
    }
    

    This method relies on an undocumented site feature which doesn't work in Firefox, for example.

    A more reliable crossbrowser method available to Chrome extensions and WebExtensions is to monitor page url changes because Google Search results page always updates its URL hash part. We'll need a background/event page, chrome.tabs.onUpdated listener, and messaging:

    • background.js

      var rxGoogleSearch = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
      chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
          if (rxGoogleSearch.test(changeInfo.url)) {
              chrome.tabs.sendMessage(tabId, 'url-update');
          }
      });
      
    • content.js

      chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
          if (msg === 'url-update') {
              onSearchUpdated();
          }
      });
      
      function onSearchUpdated() {
          document.getElementById('resultStats').style.backgroundColor = 'yellow';
      }
      
    • manifest.json: background/event page and content script declarations, "tabs" permission.

    0 讨论(0)
提交回复
热议问题