用于解析 Google 结果的 Chrome 扩展程序不起作用 [英] Chrome extension to parse Google results doesn't work

查看:30
本文介绍了用于解析 Google 结果的 Chrome 扩展程序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试验 Chrome 扩展程序机制,并试图编写一个可以操纵 Google 结果的扩展程序(添加评论、屏幕截图、网站图标等)

I've been experimenting with the Chrome extensions mechanism, and been trying to write an extension that would manipulate Google results (add comments, screenshots, favicons, etc.)

到目前为止,我已经设法编写了一个使用 RegEx 将 imgs 添加到链接的代码,并且它工作正常.

So far I've managed to write a code that uses a RegEx to add imgs to a link, and it works ok.

问题在于它不适用于 Google 结果.我在此处读到这是因为页面没有完全加载;所以我添加了一个DOMContentLoaded"监听器,但没有帮助.

The problem is that it doesn't work on Google results. I read here that it happens because the page hasn't fully loaded; so I added a 'DOMContentLoaded' listener but it didn't help.

这是我的代码(内容脚本):

Here's my code (content script):

function parse_google()  {
document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp("<a href="(.*)"(.*)</a>", "g"),
        "<img src="http://<path-to-img.gif>" /><a href="$1"$2</a>"
    );
alert("boooya!");
};
alert("content script: before");
document.addEventListener('DOMContentLoaded', parse_google(), false);    
alert("content script: end");

我收到所有警报",但它不适用于谷歌.为什么?

I get all "alerts", but it doesn't work for google. Why?

推荐答案

"DOMContentLoaded" 指的是页面的静态 HTML,但 Google 的搜索结果是使用 AJAX 获取的,因此当 "DOMContentLoaded" 事件发生时,还没有出现触发.

"DOMContentLoaded" refers to the static HTML of the page, but Google's search results are fetched using AJAX, thus are not there yet when the "DOMContentLoaded" event is triggered.

您可以使用 MutationObserver 相反,观察根节点及其后代上的childList"DOM 突变.
(如果您选择这种方法,mutation-summary 库可能会派上用场.)

You could use a MutationObserver instead, to observe "childList" DOM mutations on a root node and its descendants.
(If you choose this approach the mutation-summary library might come in handy.)

经过(非常浅的)搜索后,我发现(至少对我而言)Google 将其结果放在 divid search.以下是执行以下操作的示例扩展的代码:

After a (really shallow) search, I found out that (at least for me) Google places its results in a div with id search. Below is the code of a sample extension that does the following:

  1. 注册一个 MutationObserver 来检测插入 od div#search 到 DOM 中.

注册一个 MutationObserver 以检测 div#search 及其后代中的childList"变化.

Registers a MutationObserver to detect "childList" changes in div#search and its descendants.

每当添加 节点时,函数都会遍历相关节点并修改链接.(由于显而易见的原因,脚本忽略了

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆