0

I'm not sure what the best way to describe this is, but I'm calling the mutation observer every time the DOM changes and for some reason it keeps adding DOM to my page instead of overwriting DOM that it has already created.

To be more specific, I'm building a chrome extension that every time a user hovers their mouse over a specific word they get a div popup. This works perfectly fine without the mutationobserver but when I do add the mutationobserver it seems to add a lot of the popups every time the user hovers. This is obviously really bad...

Here is my code that I use to add the hover (codeSegment1):

jQuery(document).ready(function($) {

    $('.newHover').each(function() {    

        Tipped.create(this, "<iframe src='http://myurl.com"'></iframe>", {
            skin: "white",
            position: 'right',
            background: '#fff',
            detach: false,
            shadow: true,
        }); 

    });

});

As I said this works fine the first time...

Here is my code for the mutation observer (codeSegment2):

var arrayOfP = $("p").text();
var observer = new WebKitMutationObserver(function(mutations) {
    //Sends message to another document and the other document 
    //sends a message back to the code above (i.e Tipped.create)                
    chrome.runtime.sendMessage(arrayOfP, manageResponse); 
});
observer.observe(document.body, { 
    attributes: true, 
    childList: true, 
    characterData: true 
});

So here is what I think is happening:

  • Page loads.
  • codeSegment1 does it's thing.
  • New text is dynamically added to page
  • codeSegment2 fires
  • codeSegment1 does it's thing again, and again, and again.

I could be wrong. But I was hoping someone on here could shed some light on what's happening and how I can fix it.

Thanks.

Jacob
  • 77,566
  • 24
  • 149
  • 228
Katie
  • 741
  • 1
  • 9
  • 30
  • First, why do you use MutationObserver if it simply catches the mutations you do yourself judging by the description? Why `attributes: true` and `characterData: true`? Why the outdated spelling `WebKitMutationObserver`? Why do you ignore `mutations` parameter and send all of `arrayOfP`? Where's the code of `manageResponse()` function? Can you show the entire file on jsfiddle or at least show the part where `codeSegment2` fires? Also there's an extra wrong doublequote inside `""`. – wOxxOm Sep 15 '15 at 16:02
  • Also note that MutationObserver's callback runs in a microtask so it should be extremely simple in order not to slow down the page, otherwise you should spawn a new event task via `setTimeout(......, 0)`. Anyway the first thing is to understand the overall algorithm used in your code which so far seems wrong or rather I don't see much of it. – wOxxOm Sep 15 '15 at 16:16
  • might be related to - https://stackoverflow.com/q/31659567/104380 – vsync Nov 07 '18 at 16:44

0 Answers0