用于解析 Google 结果的 Chrome 扩展程序不起作用 [英] Chrome extension to parse Google results doesn't work
问题描述
我一直在试验 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 将其结果放在 div
和 id 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:
注册一个 MutationObserver 来检测插入 od
div#search
到 DOM 中.
注册一个 MutationObserver 以检测 div#search
及其后代中的childList"变化.
Registers a MutationObserver to detect "childList" changes in div#search
and its descendants.
每当添加 节点时,函数都会遍历相关节点并修改链接.(由于显而易见的原因,脚本忽略了
元素.
Whenever a <a>
node is added, a function traverses the relevant nodes and modifies the links. (The script ignored <script>
elements for obvious reasons.
这个示例扩展只是将链接的文本包含在 ~~
中,但您可以轻松地将其更改为您需要的任何内容.
This sample extension just encloses the link's text in ~~
, but you can easily change it to do whatever you need.
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"content_scripts": [{
"matches": [
...
"*://www.google.gr/*",
"*://www.google.com/*"
],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}],
}
content.js:
console.log("Injected...");
/* MutationObserver configuration data: Listen for "childList"
* mutations in the specified element and its descendants */
var config = {
childList: true,
subtree: true
};
var regex = /<a.*?>[^<]*</a>/;
/* Traverse 'rootNode' and its descendants and modify '<a>' tags */
function modifyLinks(rootNode) {
var nodes = [rootNode];
while (nodes.length > 0) {
var node = nodes.shift();
if (node.tagName == "A") {
/* Modify the '<a>' element */
node.innerHTML = "~~" + node.innerHTML + "~~";
} else {
/* If the current node has children, queue them for further
* processing, ignoring any '<script>' tags. */
[].slice.call(node.children).forEach(function(childNode) {
if (childNode.tagName != "SCRIPT") {
nodes.push(childNode);
}
});
}
}
}
/* Observer1: Looks for 'div.search' */
var observer1 = new MutationObserver(function(mutations) {
/* For each MutationRecord in 'mutations'... */
mutations.some(function(mutation) {
/* ...if nodes have beed added... */
if (mutation.addedNodes && (mutation.addedNodes.length > 0)) {
/* ...look for 'div#search' */
var node = mutation.target.querySelector("div#search");
if (node) {
/* 'div#search' found; stop observer 1 and start observer 2 */
observer1.disconnect();
observer2.observe(node, config);
if (regex.test(node.innerHTML)) {
/* Modify any '<a>' elements already in the current node */
modifyLinks(node);
}
return true;
}
}
});
});
/* Observer2: Listens for '<a>' elements insertion */
var observer2 = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes) {
[].slice.call(mutation.addedNodes).forEach(function(node) {
/* If 'node' or any of its desctants are '<a>'... */
if (regex.test(node.outerHTML)) {
/* ...do something with them */
modifyLinks(node);
}
});
}
});
});
/* Start observing 'body' for 'div#search' */
observer1.observe(document.body, config);
这篇关于用于解析 Google 结果的 Chrome 扩展程序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!