Javascript 在谷歌搜索结果中添加文本

Javascript 在谷歌搜索结果中添加文本,javascript,jquery,google-chrome,google-chrome-extension,Javascript,Jquery,Google Chrome,Google Chrome Extension,我正在尝试使用自定义的chrome扩展在google搜索结果中添加文本。但我得到了一个错误: 未捕获范围错误:超过最大调用堆栈大小 这是我的manifest.json "content_scripts": [ { "matches":["<all_urls>"], "js" : ["jquery.min.js", "contentscript.js"], "run_at": "document_end" } ] “内容脚本”:

我正在尝试使用自定义的chrome扩展在google搜索结果中添加文本。但我得到了一个错误:

未捕获范围错误:超过最大调用堆栈大小

这是我的manifest.json

"content_scripts": [
    {
      "matches":["<all_urls>"],
      "js" : ["jquery.min.js", "contentscript.js"],
      "run_at": "document_end"
    }
  ]
“内容脚本”:[
{
“匹配项”:[“”],
“js”:[“jquery.min.js”,“contentscript.js”],
“运行时间”:“文档结束”
}
]
contentscript.js:

function changeResultText(event) {
  $('h3.r').append('<b>bbbbbbbbbbbbbbbbbbbbbb</b>');
}

document.addEventListener('DOMNodeInserted', changeResultText);
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));
函数更改结果文本(事件){
$('h3.r')。追加('bbbbbbbbbbbbbbbbbb');
}
document.addEventListener('DomainNodeInserted',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:

function changeResultText(event) {
  $('h3.r').append('<b>bbbbbbbbbbbbbbbbbbbbbb</b>');
}

document.addEventListener('DOMNodeInserted', changeResultText);
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));

这里是一个工作示例,您可以在每个搜索结果的顶部设置自定义文本、图像

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:

function changeResultText(event) {
  $('h3.r').append('<b>bbbbbbbbbbbbbbbbbbbbbb</b>');
}

document.addEventListener('DOMNodeInserted', changeResultText);
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));

每次插入
时,您都会一次又一次地调用处理程序;event.stopPropagation()以确保事件不会继续调用已附加在此处的其他事件。每次插入
时,都会反复调用处理程序。请尝试
事件.preventDefault();event.stopPropagation()
以确保事件不会继续调用已附加到此处的其他事件。