简体   繁体   English

如何在内容脚本中修改Google搜索结果页?

[英]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.

相关问题 Google 自定义搜索 - 如何修改结果的文本? - Google Custom Search - How to modify results' text? 如何在处理 DOM 之前使用谷歌浏览器内容脚本修改 web 页面? - How can I modify a web page using google chrome content script before the DOM is processed? 如何在 Google Web 脚本的搜索结果中添加 OR AND - How to add OR AND into search results on Google Web Script 如何注入javascript和修改原生android浏览器google搜索结果 - how to inject javascript and modify native android browser google search results Google的搜索结果页是如何创建的? - How is the search results page for Google created? 如何在Google结果页面中提取搜索结果总数 - How to extract total amount of search results in Google results page Google如何在搜索引擎结果页面上呈现结果 - How does Google render it's results on the Search engine results page 修改 Google 搜索结果页面 - Modifying Google Search Results Page 如何设置Google自定义搜索以在诸如search.php之类的特定页面上显示搜索结果? - How to set the google custom search to dispaly the results of search on a paticular page like search.php? Google Apps脚本-如何获取页面内容? - Google Apps Script - How can i get the content of a page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM