Search inside forum, pretty certain there are dozens of samples.
Can you point me to one of those examples?
It is complicated – but that's because InDesign's text model is much more complicated than Illustrator's.
textVarR = app.selection.parentStory.textVariableInstances.add(LocationOptions.AFTER, app.selection); textVarR.associatedTextVariable = app.activeDocument.textVariables.item("My Name");
You insert a ("any", really) text variable code in your text, and then you associate it with the particular one you want.
Other than that, inserting the text variable in the proper place is pretty much the same as inserting text. You must provide a reference parent object – a plain text frame would not work, it needs a "text'-like object such as 'yourTextFrame.parentStory' – and "where" you want it to be inserted inside that parent object ("at the start", "at the end", or "before" or "after" a particular indexed element).
Jongware already pointed to textVariableInstances with their method add().
See ExtendScript DOM documentation by Jongware here:
Also inspect this cornucopia of documentation also by Jongware:
I tried your example but this is the error I get when I run your first line in ExtendScript with the text frame selected. I don't understand the error because it says TextFrame is an expected value.
Error: Invalid value for parameter 'reference' of method 'add'. Expected TextVariableInstance, TextFrame, EndnoteTextFrame, Story, XmlStory, Note, Cell, Footnote, Table, TextColumn, TextStyleRange, Text, InsertionPoint, Paragraph, Line, Word, Character or Change, but received TextFrame.