Home > database >  Adding an element each time a popover is drawn
Adding an element each time a popover is drawn

Time:06-20

I want to write script adding one element to other element with particular id when it appears on page. It is added to a document when user hovers over other element.

In terms of business logic: when user hovers over user name, a popver appears. I want to add a button to a child in each of appearing popovers.

I've looked on this and resembled this construction with the code below, and it works. The issue is it checks only for one element, and when it appears, ends its work. I understand, that in order to check for every element, I should remove line this.disconnect();. That, however, only causes web page to hang.

What should I do to make it work? Am I doing something wrong?

// ==UserScript==
// @name         ms_teams_integration
// @match        https://example.com/*
// @version      1.0
// @grant        none
// @run-at       document-start
// @require      https://greasyfork.org/scripts/12228/code/setMutationHandler.js
// ==/UserScript==

var teamsIcon = ""; // icon in svg format here

setMutationHandler(document, '#user-hover-email', function(nodes) {
    this.disconnect();
    nodes.forEach(function(n) {
        var emailLink = n.getElementsByTagName("a").item(0);
        var teamsLink = emailLink.cloneNode(true);
        teamsLink.setAttribute(
            "href", 
            teamsLink.getAttribute("href")
                .replace("mailto:", "https://teams.microsoft.com/l/chat/0/0?users="));
        teamsLink.setAttribute("target", "_blank");
        teamsLink.innerHTML = teamsIcon;
        n.appendChild(teamsLink);
    });
});

CodePudding user response:

It hangs because your code causes a new mutation, which is detected again and again. To prevent it, check whether the new element is already added:

    nodes.forEach(function(n) {
        if (n.__ms_teams_integration) return;
        var emailLink = n.getElementsByTagName("a").item(0);
        // ...............
        // ...............
        n.appendChild(teamsLink);
        n.__ms_teams_integration = true;
    });
  • Related