Chrome 扩展检测 Google 搜索刷新
Chrome extension detect Google search refresh
我的内容脚本如何检测 Google 搜索的刷新?
我相信这是页面的 AJAX 重新加载而不是 "real" 刷新,所以我的事件不会检测到刷新。
是否可以在 Google Chrome 扩展和 Firefox WebExtensions 附加组件中以某种方式检测到它?
Google搜索是一个动态更新的页面。有几种众所周知的方法可以检测更新:MutationObserver, timer-based approach (see waitForKeyElements wrapper),以及网站使用的事件,例如 pjax:end on GitHub.
幸运的是,Google 在 Chrome 浏览器中搜索使用 message
事件,所以这是我们的内容脚本:
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';
}
例如,此方法依赖于在 Firefox 中不起作用的未记录站点功能。
可用于 Chrome 扩展和 WebExtensions 的更可靠的跨浏览器方法是监视页面 url 更改,因为 Google 搜索结果页面始终更新其 URL 哈希部分。我们需要 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.
我的内容脚本如何检测 Google 搜索的刷新? 我相信这是页面的 AJAX 重新加载而不是 "real" 刷新,所以我的事件不会检测到刷新。
是否可以在 Google Chrome 扩展和 Firefox WebExtensions 附加组件中以某种方式检测到它?
Google搜索是一个动态更新的页面。有几种众所周知的方法可以检测更新:MutationObserver, timer-based approach (see waitForKeyElements wrapper),以及网站使用的事件,例如 pjax:end on GitHub.
幸运的是,Google 在 Chrome 浏览器中搜索使用 message
事件,所以这是我们的内容脚本:
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';
}
例如,此方法依赖于在 Firefox 中不起作用的未记录站点功能。
可用于 Chrome 扩展和 WebExtensions 的更可靠的跨浏览器方法是监视页面 url 更改,因为 Google 搜索结果页面始终更新其 URL 哈希部分。我们需要 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.