我正在尝试使用自定义Chrome扩展名在Google搜索结果中添加文字。但我收到此错误:
未捕获的RangeError:超出了最大调用堆栈大小。
这是我的manifest.json
"content_scripts": [
{
"matches":["<all_urls>"],
"js" : ["jquery.min.js", "contentscript.js"],
"run_at": "document_end"
}
]
contentscript.js:
function changeResultText(event) {
$('h3.r').append('<b>bbbbbbbbbbbbbbbbbbbbbb</b>');
}
document.addEventListener('DOMNodeInserted', changeResultText);
我该如何解决这个问题?
最佳答案
这是一个工作示例,您可以在每个搜索结果的顶部设置自定义文本,图像。
manifest.json:
{
...
"content_scripts": [
{
"js" : ["jquery.min.js", "contentscript.js"],
"css": ["contentscript.css"],
"matches": [ "\u003Call_urls>" ],
"run_at": "document_end",
"all_frames": false
}
]
...
}
contentscript.js:
console.log("Custom Script 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];
var replace = '';
while (nodes.length > 0) {
var node = nodes.shift();
if (node.tagName == "A" && node.parentElement.parentElement.className == 'rc') {
replace = "<div class=\"store-logo\">\r\n <img src='any-logo.png' width='30' height='20' > </div>";
replace += "<div class=\"cashback-text\">Any Title</div>\r\n";
replace += node.innerHTML;
node.innerHTML = replace;
} 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);
//document.addEventListener('DOMNodeInserted', observer1.observe(document.body, config));
contentscript.css:
.store-logo{
float: left;
margin-right: 10px;
height: 19px;
}
.cashback-text{
color: #f43632 !important;
}