JS “Before Capture” editor action to help to prep my draft for scripting

#1

Can someone assist me in my JS? I’m trying to accomplish the following:

  1. Create new draft in editor view
  2. Apply JS syntax to #1
  3. Add ‘script’ tag to #1

I’m able to do all of these in JS, but not all in one action. The issue is when I use the editor object followed by the draft object, the draft functions apply to the current draft open (prior to running the action) even though I use editor.activate() and editor.isActive=1, etc.

I thought it may be an issue where the action is writing the editor changes to disk before the draft is loaded in the editor view, but I get errors when using JS timeout methods and can’t figure this one out.
My code is below, appreciate the help!

// New Script Draft Action
	
// Prompt
var p = Prompt.create()
p.title = "Create New Script"
p.addTextField("draftTitle", "Draft Title", "")
p.addButton("Create")
var didSelect = p.show()
var textFieldContents = p.fieldValues["draftTitle"]
	
// Editor
editor.new()
editor.activate()
editor.isActive = 1
editor.setText("// " + textFieldContents)
editor.save()
	
// Draft
draft.languageGrammar = "JavaScript"
draft.addTag("script")	
draft.update()
#2

For the duration of an action, the draft variable is always going to point to the draft you ran the action on - it will not change based on what draft is in the editor. What you want to do is create a new draft, save it, then load it in the editor, like:

let d = Draft.create();
d.content = textFieldContents;
d.addTag("script");
d.languageGrammar = "JavaScript";
d.update(); // save new draft

// now load your new draft in editor
editor.load(d);
editor.activate();
2 Likes
#3

Ahh gotcha, thank you. This was my first ever JS script for Drafts. Makes sense. Appreciate the quick reply!