0

I am building a chrome extension to mark some words on the current page.

I have asked another question on this post to achieve this. The solution is valid but not working for my extension somehow. The replaceChild line makes the page freeze.

Why is this happening ? How can I fix this ? Any workarounds are welcomed.

here is what I have so far for my content_script javascript file content.js :

var elements = document.body.getElementsByTagName('*');

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {
        var node = element.childNodes[j],
            par = node.parentElement;

        if (node.nodeType === Node.TEXT_NODE) {
            replacer(node, par);
        }
    }
}

function replacer (node, parent) {
    var re = /Questions/;
    var str = node.nodeValue;

    if (re.exec(str) !== null) {
        var newNode = document.createElement('span');

        newNode.innerHTML = node
            .nodeValue
            .replace(/Questions/g, '<span>$&</span>');

        console.log('should replace child here !');
        parent.replaceChild(newNode, node);
    }
}

everything works fine but this line(comment the line to see) :

parent.replaceChild(newNode, node);

here is manifest.json :

{
    "manifest_version": 2,
    "name": "Search Hero",
    "description": "blablabla",
    "version": "1.0",
    "permissions": [
        "activeTab"
    ],
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "content.js"
            ],
            "run_at":    "document_end"
        }
    ]
}
Community
  • 1
  • 1
AlexB
  • 3,518
  • 4
  • 29
  • 46
  • Are you getting an error? Have you confirmed that the `parent` and `node` params are indeed correct. – Vivek Pradhan Aug 09 '16 at 06:49
  • I cannot see any error because the page freezes. The parent and node are correct(I tried commenting replaceChild and everything worked fine) – AlexB Aug 09 '16 at 06:51
  • 1
    @AlexB Why don't use use [mark.js](https://markjs.io/)? Using `innerHTML` will trigger regeneration of the DOM and destroys events! – dude Aug 09 '16 at 07:09
  • @dude I have seen mark.js, I think I will use it. It is made for that. Would I really destroy events ? I am only adding a span inside other elements... I am not sure. But yeah, the question is still interesting for me but you are right, I should definitely use mark.js – AlexB Aug 09 '16 at 07:36
  • @AlexB Yes, it indeed does destroy all events. Read more e.g. here http://www.julienlecomte.net/blog/2007/12/38/ – dude Aug 09 '16 at 08:09

0 Answers0