1

I want to write a userscript that modifies the share dialog to add an extra field:

"share a link to this question" dialog

It's easy enough to retrieve and modify this dialog whilst it's on the page, but it gets added to the DOM only after the share button is clicked, so the puzzle is how to be aware of when that's the case.

A clear (but hacky) option to me is put an event listener on share buttons, wait for them to be clicked, set a timeout for 100ms, then find & modify whatever .share-tip element exists on the page. However, I'm hoping there's a better way or a best practice identified by userscript authors.

What's the current best practice for detecting when the share dialog is open? Is there an event call exposed by the JavaScript StackExchange object which I should hook into?

1 Answer 1

3

Instead of polling for it, you can use a MutationObserver which exists for this exact thing:

var observer = new MutationObserver(function(mutations, observer) {
    for (var i = 0; i < mutations.length; i++) {
        if ($(mutations[i].target).is('.share-tip')) {
            //do your thing
        }
    }
});

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

This should fire whenever the .share-tip div appears.

You can see my SOX userscript source here and here to see how we've implemented it there if you want :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .