在插件中使用 MutationObservers

Using MutationObservers in addons

我正在尝试在我的插件中使用 MutationObserver。因此,我注入了一个内容脚本,然后设置了观察者。这在某种程度上似乎可行,而且检测到的突变似乎无法序列化为 JSON。 但实际上我想使用 this library for monitoring mutations. Explicitly this one is officially mentioned by Mozilla 关于插件中的突变监控。但这根本行不通。

所以有人在内容脚本中找到了工作突变观察器的工作示例(更好的突变摘要 - 参见 link)?

我的代码如下所示:

var observer = new MutationObserver(function (mutations) {
  self.port.emit("domModified", mutations); //I gets received as 'Array [{}]'
  mutations.forEach(function (mutation) {
    console.log(mutation.type); //printing mutation results in {}, printing mutation.type results in an actual string
    console.log(mutation.target);
    console.log(mutation.addedNodes.length);
  });
});

observer.observe(unsafeWindow.document.body, {
  attributes: true,
  subtree: true,
  characterData: true,
  childList: true
});

This somehow seems to work, also the detected mutations seem not be be serializable to JSON.

突变不可序列化,尤其是因为它们包含节点。如果您需要将内容脚本中的内容传递给主要的附加代码,您需要确保它们是 JSONable 值。

So anybody got a working example for a working mutation-observer (better mutation-summary - see link) inside a content-script?

我没用过你提到的库,但是我用了很多变异观察器;他们工作得很好。你可以在这里看到一个例子:https://github.com/ZER0/tweet-to-read It basically adds a button to every tweet in the stream that contains an external URL; and I needed the mutation observer to add the buttons also in future tweets. You can have a look to the implementation here: https://github.com/ZER0/tweet-to-read/blob/master/data/observable.js

希望对您有所帮助。