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

firefox addon webextensions - Chrome extension detect Google search refresh

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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|ww(.ww)?)/.*?[?#&]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.


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

...