简体   繁体   English

有时,遍历DOM以便正确返回字符串

[英]Traversing DOM for string returns correctly, sometimes

I am testing chrome extension development with a simple content script which traverses the DOM and returns true if a given string is found. 我正在使用一个简单的内容脚本测试chrome扩展开发,该脚本遍历DOM并在找到给定字符串时返回true。

On simple webpages the script returns correctly 100% but on more complex pages eg google search results, it may return true every 1 in 10 times on a page which has the given string. 在简单的网页上,脚本100%正确返回,但在更复杂的页面上,例如谷歌搜索结果,它可能在具有给定字符串的页面上每10次返回true。

I am using Crockfords DOM traversal algorithm and have even tried a different algorithm but it gives the same results. 我正在使用Crockfords DOM遍历算法,甚至尝试了不同的算法,但它给出了相同的结果。 I am new to extensions and Javascript and unsure if this is some kind of asynchronous problem? 我是扩展和Javascript的新手,不确定这是否是某种异步问题?

var exists = false;

function walkTheDOM(node) {
    // String search function 
    if (node.nodeType === 3)
        if (node.nodeValue.indexOf("today") > -1) 
            exists = true;

    // Continue recursive DOM traversal
    node = node.firstChild;
    while (node) {
        walkTheDOM(node);
        node = node.nextSibling;
    }
    return exists;
}

if (walkTheDOM(document.body))
    alert("String exists in page.");

Since pages' content may be dynamic (new content loaded after your code executes), you have 2 possibilities: 由于页面的内容可能是动态的(在代码执行后加载新内容),因此您有两种可能:

  1. If you need to have a decision in deterministic time, just wait a bit. 如果您需要在确定性时间内做出决定,请稍等一下。 Set a timeout from when your script starts executing and check then. 设置脚本开始执行时的超时,然后检查。

  2. If you are okay with changing the decision if a word appears later, your best bet is to run what you're already running, plus set up a listener for DOM changes and analyze the new/modified nodes. 如果您可以更改决定,如果稍后出现一个单词,最好的办法是运行您已经运行的内容,并设置DOM更改的侦听器并分析新的/修改的节点。

You can combine both methods if your strategy is "detect ASAP, give up in deterministic time". 如果您的策略是“尽快检测,在确定性时间内放弃”,则可以将两种方法结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM