我的内容脚本如何检测Google搜索的刷新?我相信这是页面的AJAX重新加载,而不是“真实的”刷新,因此我的事件不会检测到刷新。
是否可以在Google Chrome扩展程序和Firefox WebExtensions附加组件中以某种方式检测到它?
Google搜索是一个动态更新的页面。存在几种检测更新的著名方法:MutationObserver,基于计时器的方法(请参见waitForKeyElements包装器)以及该站点使用的事件,例如GitHub上的pjax:end。
幸运的是,Chrome浏览器中的Google搜索使用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哈希部分。我们需要一个背景/事件页面,chrome.tabs.onUpdated侦听器和消息传递:
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';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句