Florian Loch
Florian Loch

Reputation: 809

Using MutationObservers in addons

I am trying to use a MutationObserver inside my addon. Therefore I inject a content-script which then sets the observer. This somehow seems to work, also the detected mutations seem not be be serializable to JSON. But actually I want to use this library for monitoring mutations. Explicitly this one is officially mentioned by Mozilla regarding mutation monitoring in addons. But this doesn't work at all.

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

My code looks like this:

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
});

Upvotes: 0

Views: 675

Answers (1)

ZER0
ZER0

Reputation: 25322

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

Mutations are not serializable, especially because they contains nodes. If you need to pass something from the content script, to the main add-on code, you need to be sure they're JSONable values.

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

I never used the library you mentioned, but I used mutation observers quite a lot; and they're working quite fine. You can see an example here: 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

Hope it helps.

Upvotes: 1

Related Questions