如何在内容脚本中修改谷歌搜索结果页面

How to modify Google search results page in a content script?

本文关键字:谷歌 修改 搜索结果 脚本      更新时间:2023-09-26

我创建了一个chrome扩展,并在我的内容脚本中放置了以下代码,以删除谷歌搜索页面中的一些内容:

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) console并运行window.addEventListener('message', console.log),然后在查询输入框中执行搜索,查看控制台中出现的事件并尝试找到对您有用的事件