Chrome extension detect Google search refresh

心已入冬 提交于 2019-12-29 09:32:09

问题


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.

Is it possible to detect it somehow in both a Google Chrome extension and a Firefox WebExtensions add-on?


回答1:


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.



来源:https://stackoverflow.com/questions/39288374/chrome-extension-detect-google-search-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!