[英]How to modify Google search results page in a content script?
I have created a chrome extension and placed the following code inside my content script to remove some of the contents in the google search page: 我创建了一个chrome扩展程序,并将以下代码放入了内容脚本,以删除google搜索页面中的某些内容:
window.onload = function () {
$('.g').remove(); // This is the container for the search results in Google
}
It doesn't work even though I see it working in the Developer Console when I manually execute it. 即使我在手动执行它时在开发人员控制台中看到它正常工作,它也不起作用。
Google page loads content dynamically, so you'll have to watch for elements either with a MutationObserver, or in a setTimer callback, or -preferably- find an event the page uses to signal its update. Google页面是动态加载内容的,因此您必须使用MutationObserver或setTimer回调来监视元素,或者-最好-查找该页面用于表示其更新的事件。 Many sites use message
event, so let's hook it. 许多站点都使用message
事件,因此让我们对其进行挂钩。
content.js: 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());
}
To detect the exact signal name of a dynamically loaded webpage, open devtools ( F12 ) console and run window.addEventListener('message', console.log)
, then perform the search in the query inputbox, look at the events appearing in the console and try to find which is useful for you. 要检测动态加载的网页的确切信号名称,请打开devtools( F12 )控制台并运行window.addEventListener('message', console.log)
,然后在查询输入框中执行搜索,查看控制台中出现的事件并尝试找到对您有用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.