Difficulty with the javascript "find and replace" function for a browser application

Asked

Viewed 1,124 times

3

I’m trying to develop an extension for Chrome, and I’m still in the early stages, and at the very beginning I’m already stuck. I know very little about javascript but I try to do what I can by searching. This extension is inspired by Foxreplace of , ie, is an extension that searches for all the entries designated by the user on the page that is and replaces by any other text that the user put.

I found an extension for Chrome on and I used it as a reference, but because it’s hyper simple (just take "The Cloud" and replace it with "my Butt" -- yes, it’s very crude), I can’t follow much, besides that the code written there I still can’t interpret very well to put what I want.

What I’ve tried (from scratch):

Placed:

var str = "Texto da substituição";
var res = str.replace(/Será substituído/gim,"Substituirá");

But it doesn’t work the way I wanted it to, because in addition to only searching for the term within "Replacement Text", instead of the whole document, it also needs something to start the search by the terms, which I searched on several websites, but all I found was codes to put directly into the page’s HTML, in the tag body, which I think, if I’m not wrong, would not have contact with the extension, by being part of the page and not the application.

The extension I picked up uses walk(document.body) and then sets the function walk(node) with a "statement" (I don’t know how this is called in Portuguese) switch (node.nodeType), which, from what I’ve seen, works as expected, but needs several fixes because it fails in several different situations.

So I’d like someone to explain to me how walk, of switch and of cases the way they were used, and/or tell me how to do it that I intend in a more appropriate way for my intention. This extension that I picked up, having edited with what I know, works until well, the problem are the bugs and some things kinda inexplicable that happen with his main code, that I will only be able to, maybe, correct, when I understand the content.

Source code of the reference extension

2 answers

5


I’m assuming you’re familiar with the syntax of Javascript, if you know as a switch and case works. If I’m wrong, I suggest starting with a Javascript tutorial, or maybe asking a more specific question (like, "how does swith work in Javascript?").

In the example code posted, walk is a recursive function that "visits" an element, then visits all its sub-elements. Therefore, if your HTML is something like:

<body>
    <div id="a">
        <span id="b"></span>
        <span id="c"></span>
    </div>
    <div id="d">
        <span id="e"></span>
    </div>
    <div id="f"></div>
</body>

He will visit in that order: body, div#a, span#b, span#c, div#d, span#e, div#f. That’s what the first 3 cases do - if the element visited is of type "element, "document" or "document fragment", visit your children. This way, all the content of the document will be visited, as you want.

The other case is for dealing with text nodes. A text node is simply the textual content of an element. For example, the text nodes of the example below:

<span>Este <b>é</b> um texto <i>formatado</i>.</span>

sane:

  • In span: "This ", "a text ", "."
  • In b: "is"
  • In i: "formatted"

Every time a text node is visited it calls the handleText, which in turn takes the contents of that node (i.e. a string) and puts it into the variable v. It changes the variable v, and then assign back to the text node.

I hope this helped you understand how the example works, so you can adapt it to do what you want. For example, to make the replacement you want, just do it in the variable v, instead of creating a new variable (str).

v = v.replace(/Será substituído/gim,"Substituirá")

Move "hardcoded" text to a variable so that it is but easy to modify it:

var de = /Será substituído/gim;
var para = "Substituirá";

...

v = v.replace(de, para);

And finally find a way to assign values to these two variables. I have no experience with Chrome extensions and therefore don’t know if this is the best way, but one way would be to simply use prompt:

var de = new RegExp(prompt("Entre com o texto a procurar", "Será substituído"), "gim");
var para = prompt("Entre com o texto a substituir", "Substituirá");

...

(The second argument is a default value, which you can omit if you don’t want a)


Updating: usually a iframe does not have its content browsed - especially if it is from a different domain - for security reasons. But in the case of a browser extension, maybe this is allowed in this case. Try to deal explicitly with the iframe, modifying the first case as follows:

    next = child.nextSibling;
    if ( child.tagName === "iframe" )     // Se for um iframe...
        walk(child.contentDocument.body); // ...acessa o body do seu documento.
    else             // Senão...
        walk(child); // ...percorre normalmente.
    child = next;
  • Something I can’t understand is why this script doesn’t work on iframes, for example, the comments of the Facebook plugin. If the 4° case serves for any visible page text, because loads of water he can’t see the text inside the iframe?? I’ve tried every line of code iframeTo see if I could find the terms inside him, but nothing worked.

  • @Brunolopes From the DOM of the main page, you cannot access the content of iframes - especially from a different domain - for security reasons. Being a browser extension, maybe it has additional privileges, I don’t know... I updated my answer with more details.

2

To search the entire document you need the body content.

var search = /(Texto\s+da\s+substituição|Outro)/gi;
var replace = 'Substituir por isto';

var body = document.getElementsByTagName('body')[0];
body_content = body.innerHTML.replace(search, replace);
body.innerHTML = body_content;
  • This code worked, but only for texts that are in "raw" form, simple. It does not work in iframes, which is my main intention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.