2

I'm trying to revive Astro CB's auto edit corrections script. I've got a lot of it updated, improved, and working with Stack Exchange changes since 2015.

One thing that stuck on is setting the markdown from the new StackApps WYSIWYG editor that is currently used for answers on the meta sites. I can find the element in the page and gets its markdown with jQuery:

$('.post-editor .markdown').text()

However, I haven't figured out how to set the markdown back into the editor after modifying it. I have found the following that looks promising:

StackExchange.stacksEditor.getInstanceFromElement($('.post-editor'))

But when I run it I get:

Uncaught TypeError: t.dataset is undefined
l https://meta.stackexchange.com/Content/Js/stacks-editor.en.js?v=209d11c01c46:1

I've also tried using [0] after the jQuery selector in case the editor expects plain JavaScript objects. However this gives the same error:

StackExchange.stacksEditor.getInstanceFromElement($('.post-editor')[0])

I found another user script that wraps something like that in using, but I get the same result with:

StackExchange.using("stacksEditor",function(){StackExchange.stacksEditor.getInstanceFromElement($('.post-editor'))})

How do I get access to the StacksEditor from a user script so that I can set the markdown after editing it automatically?

1 Answer 1

2

The element (yes, it is supposed to be a plain DOM element as getInstanceFromElement expects to be able to access the dataset property on it) you are looking for is not the editor wrapper with the post-editor CSS class, but the textarea descendant:

<textarea 
    id="js-stacks-editor-content" 
    name="post-text" 
    class="d-none js-stacks-editor-backing-textarea js-post-body-field" 
    data-post-type-id="2" 
    data-min-length="" 
    data-stacks-editor-instance-id="746"
></textarea>

getInstanceFromElement accesses stacksEditorInstanceId on the dataset, and as you can see, it corresponds to the data-stacks-editor-instance-id attribute of the textarea.

Hence, the following will successfully return the instance:

const instance = StackExchange.stacksEditor.getInstanceFromElement( 
    document.getElementById("js-stacks-editor-content")
);
3
  • Nice. I can paste this into the dev console of any meta page and get results! StackExchange.stacksEditor.getInstanceFromElement($('.post-editor textarea')[0]) Jun 11, 2022 at 0:37
  • 1
    It turns out that textarea is good enough for my purposes without getting the editor instance at all. Getting the val() out of the textarea, modifying it and setting it back into the text area is sufficient. The editor just reacts to those changes without any calls into the editor or event triggering. Jun 11, 2022 at 1:06
  • @StephenOstermiller that's good to know! Frankly, given the current state of the new editor, I haven't personally worked with it extensively. Jun 11, 2022 at 1:17

You must log in to answer this question.

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