[英]How to modify Google search results page in a content script?
我创建了一个chrome扩展程序,并将以下代码放入了内容脚本,以删除google搜索页面中的某些内容:
window.onload = function () {
$('.g').remove(); // This is the container for the search results in Google
}
即使我在手动执行它时在开发人员控制台中看到它正常工作,它也不起作用。
Google页面是动态加载内容的,因此您必须使用MutationObserver或setTimer回调来监视元素,或者-最好-查找该页面用于表示其更新的事件。 许多站点都使用message
事件,因此让我们对其进行挂钩。
content.js:
// process current DOM, most probably nothing useful at this point
onGoogleSearchUpdated();
// listen to "sr" signal emitted by Google search page
window.addEventListener('message', function(e) {
console.log(e.data, e);
if (typeof e.data === 'object' && e.data.type === 'sr') {
onGoogleSearchUpdated();
}
});
function onGoogleSearchUpdated() {
console.log('Removed:', $('.g').remove());
}
要检测动态加载的网页的确切信号名称,请打开devtools( F12 )控制台并运行window.addEventListener('message', console.log)
,然后在查询输入框中执行搜索,查看控制台中出现的事件并尝试找到对您有用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.