是否可以同时 运行 两个 MutationObservers?

Is it possible to run two MutationObservers at the same time?

我正在尝试使用 Greasemonkey 为 Facebook 的 Timeline 日志 页面制作脚本。

我需要捕捉两种事件:

1) URL 更改(因为更改是在 Facebook 上用 AJAX 进行的,因此页面没有完全重新加载,也没有脚本)。

2)部分元素外观

我尝试制作两个 MutationObservers,一个用于捕获 URL 变化,另一个用于捕获元素外观。 但它似乎只触发一个(url_mutation_observer)。

这是我的一些代码:

function handling_url_change(mutations){
    mutations.forEach(function (mutation){
        if (check_timeline()){
            if (!buttons_added){
                var element = $(document).find(button_location);
                if (element && element.length > 0){
                    add_buttons();
                }
            }
        }else if (set){
            reset();
        }
    });
}

function handle_deletion(mutations){
    mutations.forEach(function (mutation){
        if (mutation.addedNodes){
            for (var i = 0; i < mutation.addedNodes.length; i++){
                if (isheader(mutation.addedNodes[i])){
                    mutation.addedNodes[i].remove()
                }else if (isactivity(mutation.addedNodes[i])){
                    delete_activity(mutation.addedNodes[i]);
                }
                return true;
            }
        }
    });
    return true;
}

/*
** Mutation observers :
*/

var url_mutation_observer = new MutationObserver(handling_url_change);

var delete_mutation_observer = new MutationObserver(handle_deletion);

我有一些问题:

1) 不是每个 MutationObserver 都捕获每个突变吗?

2) 添加一个按钮(就像我的脚本那样)算作突变吗?

3) 如果我添加一个元素,该元素具有由添加此类元素触发的回调函数。不会有递归和死循环的风险吗?

4) 是否可以使用 MutationObserver 仅捕获 URL 变化,并使用另一种元素捕获某些元素的外观? (为了确保每个人只捕捉到他需要捕捉的东西,我不知道该怎么做,我用检查页面的函数检查了 url,而不是检查突变是否是一个函数"UrlChangeMutation" 或类似的东西)。

5) 我能做什么?

注意: 如果您也想要,这里是带有 console.log() 调试调用的完整脚本。 http://dpaste.com/3NWV08J

NB2: 如果您还想要没有 console.log() 调用的脚本: http://dpaste.com/3AH8YF5

首先,请注意您的 for 循环已损坏,因为它包含无条件的 return true.

1) Isn't each MutationObserver catching every mutation?

是的,因为您正在观察 document

2) Is the addition of a button (like my script does) counted as a mutation?

当然可以。

3) If I add an element with a callback function triggered by the addition of such element. Isn't there a risk of recursion and infinite loop?

绝对。
(不过这将是一个非阻塞循环,这意味着页面可能不会冻结。)

4) Is that possible to catch only the URL change with a MutationObserver [...]?

不,这不是 MutationObservers 所做的。来自 MDN:

MutationObserver provides developers a way to react to changes in a DOM.

请注意"UrlChangeMutation or something like that"不存在。

4) [...] and to catch the appearance of only some kinds of elements with the other one?

您不能指定过滤器,但您可以在回调函数中检查受影响的元素是否符合您的条件。
该死,你可以访问每个节点的所有方法和属性,你还需要什么?

5) What could I do?

我的建议? Google 更多。
例如,"javascript on url change" 的第一个结果是:

How to detect url change

我建议您阅读 DOM,因为您似乎根本不知道那里存在的许多事情。

我有一个错误:observer.observer() 不是函数。 observer.observe() 是:http://dpaste.com/3AH8YF5#line-254