<!doctype html>
The name of the bookmark.
Forget the bookmark, resetting any associated permissions. Generally, this would be a function the user performs in the user interface, but could be useful in the case of an action which wishes to request and use a one-time bookmark and revoke permissions on completion of an action.
Get a bookmark object with the specified name. If no bookmark with the specified name exists, a new one will be created.
Generated using TypeDoc
Credential objects can be used in actions which require the user to provide a username, password and optionally a host name, to connect to a service. By using credentials objects, actions can be written to connect to arbitrary web services without hard coding credentials into the action.
When an authorize() call is made on a credential object for the first time, the user is prompted to enter their credentials, then Drafts stores those for later use. When the action is used again, there will be no prompt required and the stored credentials will be used.
Credentials objects have unique identifiers, and a single set of user credentials can be used across actions by using the same identifier.
The user can delete those credentials at any time by visiting Settings > Credentials and tapping the "Forget" button on a service.
var credential = Credential.create("My Service", "Description of the service to * appear in user prompt.");
credential.addTextField("username", "Username");
credential.addPasswordField("password", "Password");
credential.authorize();
var http = HTTP.create();
var response = http.request({
"url": "http://myurl.com/api",
"username": credential.getValue("username"),
"password": credential.getValue("password"),
"method": "POST",
"data": {
"key":"value"
},
"headers": {
"HeaderName": "HeaderValue"
}
});
Create new instance.
Unique identifier for the credentials
Optional description
Add a secure entry text field for data entry.
used to retrieve the value
label is displayed to the user
Add a text field for data entry.
used to retrieve the value
label is displayed to the user
Add a text field for configured for URL data entry.
used to retrieve the value
label is displayed to the user
Call this function after configuring, but before using host, username or password properties of a credential. If the credential object has not be previous authorized, the user will be prompted to enter their credentials before continuing. If the user has previously been prompt, this method will load previously provided information.
Deletes the credentials provided by the user. This is the same as the user visiting settings and tapping "Forget" for the credentials.
Get the value the user stored for the key, as defined in a call to add the field.
Create a credential object with the specified identifier and description. Identifiers should be unique, such that any two calls from different actions with the same identifier will return the same credentials
Unique identifier for the credentials
Optional description
Create credential already configured with host url, username and password fields.
Unique identifier for the credentials
Optional description
Create credential already configured with username and password fields.
Unique identifier for the credentials
Optional description
Generated using TypeDoc
Calendar objects are used to manipulate and create calendars in the built-in Calendars app and its associated accounts.
var calendar = Calendar.findOrCreate("Activities");
var event = calendar.createEvent();
event.title = "Dinner Party";
event.notes = "Bring side dish.";
event.startDate = Date.parse("7pm next friday");
event.endDate = Date.parse("10pm next friday");
event.isAllDay = false;
if (!event.update()) {
console.log(event.lastError);
}
// load a calendar
let cal = Calendar.find("Test");
// loop over events in the last 30 days and alert the name of each.
if (cal) {
let events = cal.events((30).days().ago(), new Date());
for (let event of events) {
alert(event.title);
}
}
A Boolean value that indicates whether you can add, edit, and delete items in the calendar.
A Boolean value indicating whether the calendar’s properties can be edited or deleted.
Create a new Event object in this calendar.
Returns array of events on the calendar between the start and end dates specified.
Save changes to the calendar.
Returns the system default calendar configured for new events.
Searches for a calendar matching the title. If none is found, return undefined
.
Searches for a calendar matching the title. If none is found, creates a new list with that title in your default calendars account. If more than one calendar with the same name exist in Calendars, the first found will be returned.
Get an array all known calendars on the device.
Generated using TypeDoc
CallbackURL objects can be used to open x-callback-url requests and wait for a response from the target app.
NOTE: If you want to open a URL in Safari or another app and do not need a response or x-callback-url support, use the app.openURL(url)
method on the App object.
// Open callback URL for each line in a draft
// Setup base Fantastical URL, with no parameters
const baseURL = "fantastical2://x-callback-url/parse/";
// split draft and loop over lines
var lines = draft.content.split("\n");
for (var line of lines) {
// create and configure callback object
var cb = CallbackURL.create();
cb.baseURL = baseURL;
cb.addParameter("sentence", line);
// open and wait for result
var success = cb.open();
if (success) {
console.log("Event created");
}
else { // something went wrong or was cancelled
console.log(cb.status);
if (cb.status == "cancelled") {
context.cancel();
}
else {
context.fail();
}
}
}
Create new instance.
The baseURL of the request. This should include the x-callback-url base URL and action, typically something like app-scheme://x-callback-url/actionName
An object contain and URL query parameters returned by the target app along with it’s callback response. For example, if the target app called x-success with the query parameters result=MyTestText
, callbackResponse would contain {"result": "MyTestText"}
.
Object containing string keys and values to be appended to the base url as query parameters. Values should not be pre-encoded, but will be encoded and added to the base URL automatically. Do not include x-callback parameters (x-success
, x-error
, x-cancel
) as these will be generated by Drafts.
The current status of the callback. Used to check outcome after open is called. Possible values:
The current URL. This is provided as a debugging property, and will output the URL including the baseURL property with any configured parameters added. This property will differ from the actual URL opened when calling open()
in that it will not contain the x-success
, x-error
and x-cancel
parameters which are added dynamically at the time open()
is called.
If true, the script will pause and wait for the x-success
, x-error
or x-cancel
response from the app being targeted by the URL. If false, execution of the script/action will continue immediately and no response/results will be available.
Add a query parameter for the outgoing URL. FIXME: can the value be anything?
Opens the URL with associated parameters, and waits for a callback response. Returns true if an x-success response was received from the target app, otherwise false. If false, use the "status" property to determine the type of failure.
Creates a new CallbackURL object.
Generated using TypeDoc
A single global "context" object is available to scripts to control flow of the currently running action.
It is important to understand that cancel()
and fail()
will not immediately stop script, just stop any further action steps from being performed.
// test for logical condition before continuing
if (!validationCondition) {
context.fail();
}
// code below will still run.
// if a "Run Workflow" step preceded this script, lets look for a result
var response = context.callbackResponses[0];
if (response) {
// Workflow returns one "result" parameter, other apps may use other values.
var result = response["result"];
if (result) {
// so something with the result
}
}
If AppleScripts run using the AppleScript object return values, they will be converted to JavaScript object and stored in this array. See AppleScript docs for details.
If Callback URL or Run Shortcut action steps using the "Wait for response" option have been run in steps before the script step in an action, and the target app returned to Drafts using an x-success callback, this object will contain an array of objects with the parsed query parameters included in those responses, in the order they were received.
If HTML Preview makes calls to Drafts.send(key, value)
those values are stored in this object by key
.
Used only when calling a Drafts action from another app via x-callback-url with a /runAction
URL. Any parameters set via this method will be included as query args when calling the provided x-success
parameter. As an example, the below:
context.addSuccessParameter("a", "1");
context.addSuccessParameter("b", "2");
Would result in the parameters ?a=1&b=2
being added to the x-success
callback.
The name for the parameter
A string value for the parameter. Do not URL encode this value, it will be encoded when added to the callback URL.
Tell the context to cancel the action at the end of the script execution. If called, at the end of the script the action will be stopped. No subsequent action steps in the action will run, and the action still stop silently - no notification banners, sounds, etc. If a message is included it will be added to the action log to explain the cancellation.
Tell the context to fail the current action. In effect this is the same as cancel()
but an error notification will be shown. If a message is included it will be added to the action log to explain the cancellation.
Generated using TypeDoc
Dropbox objects can be used to work with files in a Dropbox account. The read
and write
methods are simple wrappers for uploading and reading content of files on Dropbox.
For advanced uses, the rpcRequest
, contentUploadRequest
and contentDownloadRequest
methods enable direct use of any Dropbox API 2.0 endpoints. These methods are an advanced feature which return raw results from the Dropbox API and may require advanced understanding of the API to process the results. They do enable full access to the API, however, which enabled things like querying files, listing folder contents, uploading to Paper, etc. For details on availalbe methods, see Dropbox API documentation. In the case of all of these methods Drafts takes care of the OAuth request signing and authentication process when necessary.
// create Dropbox object
var db = Dropbox.create();
// setup variables
var path = "/test/file.txt";
var content = "text to place in file";
// write to file on Dropbox
var success = db.write(path, content, "add", true);
if (success) { // write worked!
var dbContent = db.read(path);
if (dbContent) { // read worked!
if (dbContent == content) {
alert("File contents match!");
}
else {
console.log("File did not match");
context.fail();
}
}
else { // read failed, log error
console.log(db.lastError);
context.fail();
}
}
else { // write failed, log error
console.log(db.lastError);
context.fail();
}
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
Execute a request against the Dropbox API for an endpoint of Content Download type. For successful requests, the HTTPResponse object will contain an raw data in the responseData
property and, if the data can be converted to a string value, the text version in the responseText
property. The HTTPResponse otherData
property will contain a Javascript object decoded from the JSON returned in the Dropbox-API-Result
header. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
Object containing options for the request.
Execute a request against the Dropbox API for an endpoint of Content Upload type. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Dropbox as appropriate to the request made. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
Object containing options for the request.
Reads the contents of the file at the with the file name, in the parent folder, as a string. Returns undefined
value if the file does not exist or could not be read.
Path related to root of Dropbox folder.
Execute a request against the Dropbox API for an endpoint of RPC type. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Dropbox as appropriate to the request made. Refer to Dropbox's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
Object containing options for the request.
Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!
Path related to root of Dropbox folder.
Text to write to file.
Either "add" or "overwrite" to determine if the write method should overwrite an existing file at the path if it exists.
Creates a new Dropbox object.
used to identify a Dropbox account. Typically this can be omitted if you only work with one Dropbox account in Drafts.
Generated using TypeDoc
A global editor
object is available in all action scripts. This object allows manipulation of the main editing window in Drafts, altering the text, text selections, or loading a different draft into the editor, etc.
Typically scripting actions that work like custom keyboard commands and similar will utilize the editor functions to manipulate text.
NOTE: Generally speaking, editor methods are best used for quick text manipulations of the type used in the extended keyboard. Most substantial updates to draft content are better applied using the draft
object.
Is editor current focused for editing.
Access or set current link mode status.
Array of navigation markers in the text. Navigation markers are defined by the syntax definition in use in the editor, and are used in the Navigation feature.
Access or set current pinning status for editor.
Returns the current tab string is use. This could be 2 spaces, 4 spaces, or \t
depending on the editor preferences for the current syntax. Useful in actions, such as indent/outdent actions, which need to insert or remove indentation and want to match the options of the current syntax.
Array of recent drafts. This is the same list as used in the navigation features of the editor, and is in reverse order, so that the first index in the array is the previous draft loaded in the editor.
Access or set current typewriter scrolling status.
Request focus for the editor. This will dismiss other views and show the keyboard on the currently loaded draft. Useful if an action opens user interface elements or otherwise causes the editor to resign focus and you would like to return to editing at the end of the action's execution.
Opens the arrange mode view with the passed text for arranging. Returns the arranged text if the user makes changes and taps "Done", the original text if the user cancels.
The text to arrange
String containing result of arrange. If user cancels, it will be the same as the original text passed.
Resign focus for the editor. If the editor text view is currently focused for editing (e.g. showing keyboard), resign focus.
Open dictation interface, and return the result as a string. The string will be empty if user cancels.
the preferred locale can be passed in the format "en-US" (U.S. English), "it-IT" (Italian-Italian), "es-MX" (Mexican Spanish), etc.
The accepted dictation text.
Expand the range provided to the nearest beginning and end of the lines it encompasses.
Get the current selected text range extended to the beginning and end of the lines it encompasses.
Get text range that was last selected.
Get text range that was last selected.
Get the full text currently loaded in the editor.
Get the substring in a range from the text in the editor.
Loads an existing draft into the editor.
The next navigation marker in the editor, relative to the character location. This is a convenience method to assist in navigating by marker.
The previous navigation marker in the editor, relative to the character location. This is a convenience method to assist in navigating by marker.
Creates a new blank draft and loads it into the editor.
Apply redo action to editor, if one is available.
Save any current changes to the draft.
Open document scanning camera to scan documents and OCR, returning the result as a string. The string will be empty if user cancels, or document scanning is not available.
The text recognized in the OCR of the scanned document.
Update the text selection in the editor by passing the start location and the length of the new selection.
Replace the contents of the last text selection with a string.
Replace the contents of the editor with a string.
Replace the text in the passed range with new text.
Open arrange mode in editor. This is a non-blocking method and returns immediately. It is intended only to mimic the tapping of the arrange button. Use editor.arrange(text)
to wait for a result.
Open dictation mode in editor. This is a non-blocking method and returns immediately. It is intended only to mimic the tapping of the dictate button. Use editor.dictate()
to wait for a result and use it in further scripting.
Open find mode in editor.
Open Opens audio transcription window. If file is selected and transcribed, returns text.
The text recognized in the audio transcription.
Apply undo action to editor, if one is available.
Generated using TypeDoc
Generated using TypeDoc
The alarms assigned to the event, if any.
Attendees of the event as an array of objects in the format:
{
"isCurrentUser": false,
"name": "John Appleseed",
"status": "accepted",
"type": "person",
"role": "required"
}
Availability for scheduling. Not supported by all Calendar servers.
The calendar which this event resides in.
Original creation date of the event.
End date of the event.
Returns true if the event has any alarms.
Unique identifier for the event
Flag for all day events.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
Last change to the event.
Location of the event.
Notes associated with the event.
Start date of the event.
The title of the event.
URL associated with the event. Setting URL value will fail if the value is not a valid URL.
Add an alarm object to the event. Be sure to update()
to save after adding alarms.
Open the event in the system event editing card. The user will be able to modify/edit the event values and add to a calendar from this view. Returns true if the event was saved, false if the user canceled or deleted the event.
Remove any assigned alarms from the event.
Save the event. Returns true if the event is successfully saved in Calendars.
Generated using TypeDoc
Display of HTML Preview window, the same as the HTMLPreview action step. Returns true if user closed preview with the "Continue" button, false if the user cancelled.
let html = "<html><body>My Document</body></html>"
let preview = HTMLPreview.create();
if (preview.show(html)) {
// continue button was pressed
}
else {
// cancel button was pressed
}
Create new instance.
Hides the toolbars and Cancel
/ Continue
buttons in the preview window. For use only when combined with JavaScript flow control in the HTML preview. See docs for details.
Open HTML Preview window displaying the HTML string passed.
The HTML content to display. Should be complete HTML document.
Create new instance.
Generated using TypeDoc
The OutlookMessage object can be used to create and send mail messages through Outlook.com integrated accounts, similar to those created by a Outlook action step. Creating and sending these messages happens in the background, with no user interface, so messages must be complete with recipients before calling send()
. Sending is done via the Microsoft Graph API. Outlooks accounts are authenticated when used for the first time using OAuth - to use more than one account, call create with different identifier parameters.
let message = OutlookMessage.create();
message.toRecipients = ["joe@sample.com", "Jim Test <jim@test.com>"];
message.subject = "My test message";
message.body = "Body text";
var success = message.send();
if (!success) {
console.log("Sending outlook message failed");
context.fail();
}
Create new instance.
Array of email addresses to use as BCC:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
Body text of the mail message. Can be plain text or HTML if the isBodyHTML
property is set to true
.
Array of email addresses to use as CC:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
whether to treat the body string and plain text or HTML. When set to true
, the body
property should be set to full valid HTML.
Array of email addresses to use as To:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
Send the mail message via the Microsoft Graph API.
create a new object.
notes which for Outlook account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.
Generated using TypeDoc
Drafts includes a full version of the MultiMarkdown 6 engine to render Markdown text to HTML and other supported formats. For details on the meaning of the various options, refer to MultiMarkdown documentation.
var inputString = "# Header\n\nMy **markdown** text";
var mmd = MultiMarkdown.create();
mmd.format = "html";
mmd.criticMarkup = true;
var outputString = mmd.render(inputString);
Create new instance.
defaults to false
defaults to false
defaults to false
defaults to false
defaults to true
Specify output format. Valid values are:
html
: HTML. This is the default Markdown output.epub
: ePublatex
: LaTeXbeamer
memoir
odt
: Open document formatmmd
defaults to false
defaults to true
defaults to false
defaults to false
defaults to true
defaults to false
defaults to true
defaults to false
defaults to false
Takes Markdown string passed and processes it with MultiMarkdown based on the properties and format selections on the object.
Create object
Generated using TypeDoc
Wraps an array of todo and/or project items and encodes them into a URL for use to send the request to Things.
The TJS* JavaScript objects are wrappers around an open source Swift library provided by Cultured Code, with a few modifications to work in JavaScript. In all cases, nothing is committed to Things until the the items are wrapped in a TJSContainer, and the URL it generates called to send the data to Things. This is best done with Drafts’ CallbackURL
object (see example below).
For more information about what values Things understands in these objects, refer to their URL scheme documenation.
// create a Things Project
var project = TJSProject.create();
project.title = "My Project From Drafts";
project.notes = "Let's do this stuff";
// create and add a heading to the project
var heading = TJSHeading.create();
heading.title = "First Heading";
project.addHeading(heading);
// add todos to the project
var todo1 = TJSTodo.create();
todo1.title = "My first todo";
todo1.when = "today";
project.addTodo(todo1);
var todo2 = TJSTodo.create();
todo2.title = "My second todo";
todo2.when = "tomorrow";
project.addTodo(todo2);
// create a container to handle creation of Things URL
var container = TJSContainer.create([project]);
// Use CallbackURL object to open URL in Things.
var cb = CallbackURL.create();
cb.baseURL = container.url;
var success = cb.open();
if (success) {
console.log("Project created in Things");
}
else {
context.fail();
}
The full URL with encoded TJSContainer parameters.
Generated using TypeDoc
GoogleDrive objects can be used to work with files in Google Drive accounts.
// create GoogleDrive object
var drive = GoogleDrive.create();
// setup variables
var fileName = "MyTestFile";
var parent = ""; // root of drive
var content = "text to place in file";
// write to file on GoogleDrive
var success = drive.write(fileName, parent, content);
if (success) { // write worked!
var driveContent = drive.read(fileName, parent);
if (driveContent) { // read worked!
if (driveContent == content) {
alert("File contents match!");
}
else {
console.log("File did not match");
context.fail();
}
}
else { // read failed, log error
console.log(drive.lastError);
context.fail();
}
}
else { // write failed, log error
console.log(drive.lastError);
context.fail();
}
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
Reads the contents of the file at the with the file name, in the parent folder, as a string. Returns undefined
value if the file does not exist or could not be read.
Name of folder in the root of the Google Drive, or ""
for root. FIXME: optional?
Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!
Name of folder in the root of the Google Drive, or ""
for root.
Text to write to file.
Creates a new GoogleDrive object.
used to identify a GoogleDrive account. Typically this can be omitted if you only work with one GoogleDrive account in Drafts.
Generated using TypeDoc
Drafts includes Discount-based, GitHub flavored Markdown parser based on GHMarkdownParser. For details on the meaning of the various options, refer to Markdown documentation.
var inputString = "# Header\n\nMy **markdown** text";
var md = GitHubMarkdown.create();
var outputString = md.render(inputString);
Create new instance.
defaults to false
defaults to true
defaults to true
defaults to false
defaults to true
defaults to true
defaults to false
Takes Markdown string passed and processes it with GitHub Markdown parser based on the property selections on the object.
create a new object.
Generated using TypeDoc
Drafts defines a single global device
object which provides access to information about the current device.
// get system info from device object
var model = device.model;
var system = device.systemName;
var osVersion = device.systemVersion;
var batteryLevel = device.batteryLevel;
// create and display it in an alert
var s = "Model: " + model + "\n";
s = s + "System: " + system + "\n";
s = s + "OS: " + osVersion + "\n";
s = s + "Battery: " + batteryLevel;
alert(s);
// branch logic based on platform
if (device.systemName == 'macOS') {
// do something only on Mac
}
else {
// do something only on iOS
}
Current battery level as a number between 0.0 and 1.0
Model of current device.
Name of current OS.
Version of current OS.
Generated using TypeDoc
Script integration with Notion. This object handles OAuth authentication and request signing. The entire Notion REST API can be used with the request
method.
// list pages which have been shared with the Drafts integration
// API Docs: https://developers.notion.com/reference/post-search
let endpoint = "https://api.notion.com/v1/search"
let notion = Notion.create();
let result = notion.request({
"url": endpoint,
"method": "POST",
"data": {
"filter": {
"value": "page",
"property": "object"
}
}
});
// result has JSON payload
// with page properties
if (result.statusCode == 200) {
alert(`Notion Pages Loaded:
\({result.responseText}</span>`)
}
<span class="hljs-keyword">else</span> {
alert(`Notion Error: <span class="hljs-variable">\){result.statusCode}
${notion.lastError}`);
context.fail();
}
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
If a function succeeds, this property will contain the last response returned by Notion. The JSON returned by Notion will be parsed to an object and placed in this property. Refer to Notion API documentation for details on the contents of this object based on call made.
Execute a request against the Notion API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Notion as appropriate to the request made. Refer to Notion's API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
an object configuring the request.
A JavaScript object containing data to be encoded into the HTTP body of the request. Refer to API documentation for appropriate information to include.
An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those. Drafts will automatically include required authentication and versioning headers.
The HTTP method, like "GET", "POST", etc.
An object containing key-values to be added to the request as URL parameters.
The full URL to the endpoint in the Notion REST API.
Creates a new Notion object.
Optional string value used to identify a Notion account. Typically this can be omitted if you only work with one Notion account in Drafts. Each unique identifier used for Notion accounts will share credentials - across both action steps and scripts.
Generated using TypeDoc
Represents a Things heading within a project. See TJSContainer documentation for details on making requests to Things.
Generated using TypeDoc
Create new instance.
Array of email addresses to use as BCC:
recipients.
Body text of the mail message. Can be plain text or HTML if the isBodyHTML
property is set to true
.
Array of email addresses to use as CC:
recipients.
whether to treat the body string and plain text or HTML. When set to true
, the body
property should be set to full valid HTML.
Indicates if the message object has already been sent.
If true
, the mail will be sent in the background using a web service rather than via Mail.app - but will come from drafts5@drafts5.agiletortoise.com
. Defaults to false
.
One of the following values:
send()
has been called.Subject line
Array of email addresses to use as To:
recipients.
Send the mail message. This will open the Mail.app
sending window. Returns true
if the message was sent successfully or false
if not - if, for example, the user cancelled the mail window.
Create Mail
object
Generated using TypeDoc
Create new instance.
Body text of the mail message.
true/false flag indicated if the message object has already been sent.
One of the following strings
send()
has been called.Subject line. Only used if subject is enabled in Messages settings on the device.
Array of phone numbers and email addresses to use as To:
recipients.
Send the message. This will open the Messages.app
sending window. Returns true
if the message was sent successfully or false
if not - if, for example, the user cancelled the message window.
Instantiate Message
object
Generated using TypeDoc
The GmailMessage object can be used to create and send mail messages through Gmail accounts, similar to those created by a Gmail action step. Creating and sending these messages happens in the background, with no user interface, so messages must be complete with recipients before calling send(). Sending is done via the Gmail API. Gmail accounts are authenticated when used for the first time using OAuth - to use more than one account, call create with different identifier parameters.
let message = GmailMessage.create();
message.toRecipients = ["joe@sample.com"];
message.subject = "My test message";
message.body = "Body text";
var success = message.send();
if (!success) {
console.log("Sending gmail failed");
context.fail();
}
Create new instance.
Array of email addresses to use as BCC:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
Body text of the mail message. Can be plain text or HTML if the isBodyHTML
property is set to true
.
Array of email addresses to use as CC:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
whether to treat the body string and plain text or HTML. When set to true
, the body
property should be set to full valid HTML.
Array of email addresses to use as To:
recipients. Each entry can be a valid email address, or a name and email in the format Name<email>
.
Send the mail message via the Gmail API.
create a new object.
notes which for Gmail account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.
Generated using TypeDoc
Script integration with Twitter. The updateStatus
method is a convenience method for posting a tweet, but the entire Twitter API can be used with the request method, which handles OAuth authentication and authorization.
// create twitter object
var twitter = Twitter.create();
// post tweet
var success = twitter.updateStatus("My tweet content!");
if success {
console.log(twitter.lastResponse);
}
else {
console.log(twitter.lastError);
context.fail();
}
Create new instance.
Execute a request against the Twitter API. For successful requests, the [[[HTTPResponse]] object will contain an object or array or objects decoded from the JSON returned by Twitter as appropriate to the request made. Refer to Twitter’s API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
an object with the following properties:
Post a status update (tweet) to Twitter. Returns true
if successful, false
if not. After success the lastResponse
object can be used to inspect response and get details such as the ID of the tweet created. Refer to Twitter API POST /status/update documentation for response details.
Creates a new Twitter object. Identifier is a optional string value used to identify a Twitter account. Typically this can be omitted if you only work with one Twitter account in Drafts. Each unique identifier used for Twitter accounts will share credentials - across both action steps and scripts.
Generated using TypeDoc
OneDrive objects can be used to work with files in a OneDrive account.
// create OneDrive object
var drive = OneDrive.create();
// setup variables
var path = "/test/file.txt";
var content = "text to place in file";
// write to file on OneDrive
var success = drive.write(path, content, false);
if (success) { // write worked!
var driveContent = drive.read(path);
if (driveContent) { // read worked!
if (driveContent == content) {
alert("File contents match!");
}
else {
console.log("File did not match");
context.fail();
}
}
else { // read failed, log error
console.log(drive.lastError);
context.fail();
}
}
else { // write failed, log error
console.log(drive.lastError);
context.fail();
}
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined.
Reads the contents of the file at the path as a string. Returns undefined value if the file does not exist or could not be read. Paths should begin with a /
and be relative to the root directory of your OneDrive.
Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!
Paths should begin with a /
and be relative to the root directory of your OneDrive
Text to place in the file
If false
, an existing file will not be overwritten
Optional identifier for OneDrive account to use. This string is an arbitrary value, but we recommend using the email address you wish to associate with the script. Each unique identifier will be associated with its own Credential.
Generated using TypeDoc
macOS only. Requires Drafts 19 or greater.
ShellScript objects can be used to execute Unix shell scripts.
// define text of bash script
let script = `#!/bin/bash
echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
`;
let runner = ShellScript.create(script);
if (runner.execute(["1", "2"])) {
alert("STDOUT: " + runner.standardOutput);
}
else {
alert("STDERR: " + runner.standardError);
}
let script = #!/usr/bin/env ruby
ARGV.each do |a|
puts "Argument: #{a}"
end
;
let runner = ShellScript.create(script);
if (runner.execute(["1", "2"])) {
alert("STDOUT:\n" + runner.standardOutput);
}
else {
alert("STDERR:\n" + runner.standardError);
}
Note: When executed, scripts are saved to temporary files in the Drafts' script directory at ~/Library/Application Scripts/com.agiletortoise.Drafts-OSX
and run. Scripts should not be written to make assumptions about their location in the file system (e.g. using relative paths). The first time a script is executed, the user will be asked to grant permissions to the script directory.
Create new instance.
Content sent to standard error during the execution of the script
Content sent to standard output during the execution of the script
Executes the shell script.
An array of string arguments to pass to the script. These will appear to the script as command line arguments would.
true
if the script was executed without error, false
if not.
Convenience method to create a ShellScript object.
A string containing the shell script. This should contain the appropriate "she bang" to trigger the appropriate scripting language/shell.
Generated using TypeDoc
Represents a Things project, with headings and todo items. See TJSContainer documentation for details on making requests to Things.
Generated using TypeDoc
Script integration with Medium.com. This object handles OAuth authentication and request signing. The entire Medium REST API can be used with the request
method, and convenience methods are provided for common API endpoints to get user information, list publications and post.
If an API calls fails, typically the result will be an undefined
value, and the lastError
property will contains error detail information for troubleshooting.
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
If a function success, this property will contain the last response returned by Medium. The JSON returned by Medium will be parsed to an object and placed in this property. Refer to Medium API documentation for details on the contents of this object based on call made.
Create a post in the user's Medium stories. See API docs for details on what should be included in the options.
Get User information for current authenticated user. This will include the id
property needed for other calls.
Get list of publications for current authenticated user.
Execute a request against the Medium API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Medium as appropriate to the request made. Refer to Medium API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
an object configuring the request.
A JavaScript object containing data to be encoded into the HTTP body of the request.
An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.
The HTTP method, like "GET", "POST", etc.
An object containing key-values to be added to the request as URL parameters.
The full URL to the endpoint in the Medium REST API.
Creates a new Medium object.
Optional string value used to identify a Medium account. Typically this can be omitted if you only work with one Medium account in Drafts. Each unique identifier used for Medium accounts will share credentials - across both action steps and scripts.
Generated using TypeDoc
Prompts allow the creation and display of custom dialogs to request information or confirmation from the user.
var p = Prompt.create();
p.title = "Hello";
p.message = "World!";
p.addTextField("textFieldName", "Label", "");
p.addDatePicker("myDate", "Start date", new Date(), {
"mode": "date"
});
p.addButton("First");
p.addButton("Second");
var didSelect = p.show();
var textFieldContents = p.fieldValues["textFieldName"];
var startDate = p.fieldValues["myDate"];
if (p.buttonPressed == "First") {
// do something
}
Create new instance.
If true, a "Cancel" button will be included in the dialog. Defaults to true
. If the user selects the cancel button, the show()
method will return false
. If false
, no cancel button will be displayed and the user must select one of the button name options.
A longer message explaining the purpose of the dialog, if needed.
Short title.
After the show()
method is called, this property will contain the name of the button selected by the user.
After the show()
method is called, this property will contain values from any fields added to the prompt. The dictionary keys will be the names of the fields as passed in when they were created, and the value will be the current contents of that field. They type of data depends on the type of field.
Add a button to the array of buttons to be displayed. All buttons should be created before calling show()
.
only needed to associate a different value than will be displayed in the button. For example, if you call prompt.addButton("First Button", 1)
, after calling prompt.show()
if that button is pressed, the prompt.buttonPressed
will contain the number value 1
.
used to specify a single button which will be pinned to the bottom of the prompt and respond to cmd + return
as the default button. If only one button is added to a prompt, it is assumed to be the default.
Add a date and/or time picker to the prompt, with the arguments as below. The fieldValues
entry for this will be a date object.
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
The initial date to selected for the field. Minimum and maximum values should be defined in options.
A dictionary of options for configuring the text field.
Add an information text label to the prompt.
Identifier for the field.
The text of the label.
A dictionary of options for configuring the text field.
Same as addTextField, but the input field will be password masked.
Add a picker to the prompt, with the arguments as below. Picker can contain multiple rows. The fieldValues
entry for this will be a array of selected index values object.
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
The values to display in the picker. Should be an array containing arrays of string values, each sub-array representing a column in the picker. Example two column picker: [["Item 1", "Item 2"],["Column 2 Item 1", "Column 2 Item 2"]]
Array of zero-based index values to set the initial selected row in each column.
Add a select control. Returns an array of string values in fieldValues
.
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
The array of string values that will be available to select.
Array of string values that should be initially selected when the prompt is displayed. All values in this array should match values in the values
array.
If false
, selecting a value will deselect all other values. If true
, the user may select multiple items.
Add an on/off toggle switch. The fieldValues
entry for this item will be a boolean indicating whether the switch was on.
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
indicate if the switch should be on or off when initially displayed.
Add a text input field to the prompt
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
The initial text contents for the field.
A dictionary of options for configuring the text field.
Should system autocorrect be enabled in field, Default: true
Placeholder text to use when field is empty
If true, focus this field when prompt is displayed
Add a text input field to the prompt
Identifier for the field. This will be used as the key in the fieldValues
dictionary to access the contents of the field after calling show()
.
User-friendly text label to place next to the field.
The initial text contents for the field.
A dictionary of options for configuring the text field.
Should system autocorrect be enabled in field, Default: true
If true, focus this field when prompt is displayed
Displays the prompt. Returns true
if the user selected one of the buttons in the buttons array, false
if the user selected the "Cancel" button. After the dialog has been shown, the buttonPressed
property will contain the name of the button selected by the user.
Create new instance.
Generated using TypeDoc
Box objects can be used to work with files in a Box.com account.
// create Box object
var drive = Box.create();
// setup variables
var path = "/test/file.txt";
var content = "text to place in file";
// write to file on Box
var success = drive.write(path, content, false);
if (success) { // write worked!
var driveContent = drive.read(path);
if (driveContent) { // read worked!
if (driveContent == content) {
alert("File contents match!");
}
else {
console.log("File did not match");
context.fail();
}
}
else { // read failed, log error
console.log(drive.lastError);
context.fail();
}
}
else { // write failed, log error
console.log(drive.lastError);
context.fail();
}
Create new instance.
Reads the contents of the file at the path as a string. Returns undefined
value if the file does not exist or could not be read. Paths should begin with a /
and be relative to the root directory of your Box.com account.
Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!
Paths should begin with a /
and be relative to the root directory of your Box
Text to place in the file.
If false, an existing file will not be overwritten.
Creates a new Box object. Identifier is a optional string value used to identify a Box.com account. Typically this can be omitted if you only work with one Box.com account in Drafts.
Generated using TypeDoc
Represents a Theme definition available in the current installation of Drafts.
let theme = Theme.find("builtIn", "dark");
app.lightTheme = theme;
URL which can be used to install this Theme in another installation of Drafts. Useful for sharing and backups.
The name of the theme definition.
The type (builtIn, custom, file) of the theme definition.
Get list of all available themees.
Generated using TypeDoc
The XMLRPC object is a convenience method to provide an easy way to XML-RPC web services. The request function takes care of converting native Javascript objects and values to the XML parameters required for the XML-RPC interface, and converts the XML responses returned to Javascript objects.
It will also return faults parsed to error messages in the response if necessary.
This object is suitable for communication with a number of popular XML-RPC interfaces, including the MetaWeblog API. WordPress also offers its own XML-RPC interface, which can be used via this object, or the convenience wrapper WordPress
object.
// DEMO of XML-RPC
// Calls example method on http://xml-rpc.net/index.html
let url = "http://www.cookcomputing.com/xmlrpcsamples/RPC2.ashx";
let methodName = "examples.getStateName";
let params = [20];
let response = XMLRPC.request(url, methodName, params);
if (response.success) {
alert(JSON.stringify(response.params));
}
else {
alert("Fault: " + response.faultCode + ", " + response.error);
context.fail();
}
Make an XML-RPC request.
The full URL of the XML-RPC host endpoint being called.
Name of the method to call. Supported values are specific to the services provided by the host.
The parameters to pass to the request. This should be an array of values, in the proper order, as specified by the documentation of the host being called. This array will be encoded into XML-RPC parameters in XML format by the method - only raw javascript values should be provided.
Generated using TypeDoc
Represents a Things todo item. Todos can be added a project or directly to a container. See TJSContainer documentation for details on making requests to Things.
Generated using TypeDoc
When running a Script action step, a single script
object will be in context to reference the currently running script.
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
async function f() {
let promise = new Promise((resolve, reject) => {
sleep(1000);
resolve("done!")
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
script.complete();
}
f();
Inform Drafts the current script has completed execution. Used in combination with the "Allow asynchronous execution" option of the Script step type. If your script step has the asynchronous option enabled, you must call script.complete()
to indicate completion or the script will timeout and fail.
Generated using TypeDoc
Script integration with Todoist. This object handles OAuth authentication and request signing. The entire Todoist REST API can be used with the request method, and convenience methods are provided for common API endpoints to manage tasks, projects, comments and labels.
The quickAdd
method is mostly likely what you are looking for to create tasks as it supports the shorthand the task entry box in Todoist supports to parse projects, etc.
Other methods are direct mappings of the REST API calls provided by Todoist. Most take an options
parameter which is a javascript object containing the parameters to be passed to the API, and and the method decodes the JSON response from Todoist and returns it as a Javascript object (or array of objects) with the values as specified in the Todoist API docs.
If an API calls fails, typically the result will be an undefined
value, and the lastError
property will contains error detail information for troubleshooting.
See Examples-Todoist action group in the Action Directory.
// create Todoist object
let todoist = Todoist.create();
// create task in inbox
todoist.createTask({
"content": "My Task Name",
"due_string": "Next wednesday"
});
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
If a function succeeds, this property will contain the last response returned by Todoist. The JSON returned by Todoist will be parsed to an object and placed in this property. Refer to Todoist API documentation for details on the contents of this object based on call made.
Create new comment. Todoist API documentation
Get comment. Todoist API documentation
Get all comments. Todoist API documentation
Update comment. Todoist API documentation
Create new labels. Todoist API documentation
Get label. Todoist API documentation
Get all labels. Todoist API documentation
Update label. Todoist API documentation
Text to use to create the task. Supports Todoist quick add notation for specifying projects, priority, labels, etc. just as if you were using the Todoist quick add window.
Optional text to attach as a comment with the task.
Optional natural language date specifying for creating a task reminder.
Optional dictionary of additional parameters to include in the request.
Object containing respose data from Todoist.
Execute a request against the Todoist API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by Todoist as appropriate to the request made. Refer to Todoist’s API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
an object configuring the request.
A JavaScript object containing data to be encoded into the HTTP body of the request.
An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.
The HTTP method, like "GET", "POST", etc.
An object containing key-values to be added to the request as URL parameters.
The full URL to the endpoint in the Todoist REST API.
Creates a new Todoist object.
Optional string value used to identify a Todoist account. Typically this can be omitted if you only work with one Todoist account in Drafts. Each unique identifier used for Todoist accounts will share credentials - across both action steps and scripts.
Create new project. Todoist API documentation
Get project. Todoist API documentation
Get all projects. Todoist API documentation
Update project. Todoist API documentation
Create new section. Todoist API documentation
Get project sections. Todoist API documentation
Get section. Todoist API documentation
Get all sections. Todoist API documentation
Update section. Todoist API documentation
Close task (mark complete)
Create new task. Todoist API documentation
Get active task. Todoist API documentation
Get active tasks. Todoist API documentation
Reopen task (mark incomplete)
Update active task. Todoist API documentation
Generated using TypeDoc
Alarms are alerts which can be attached to Reminder and Event objects.
let list = ReminderList.findOrCreate("Errands");
let reminder = list.createReminder();
reminder.title = "Get more paper towels";
let alarm = Alarm.alarmWithDate((3).days().fromNow());
reminder.addAlarm(alarm);
reminder.update();
Alarm set to remind at a specific date/time.
Generated using TypeDoc
ReminderList objects are used to manipulate and create lists in the built-in Reminders app.
const list = ReminderList.findOrCreate("Groceries");
let reminder = list.createReminder();
reminder.title = "Bananas";
reminder.notes = "Get slightly green ones."
reminder.update();
Reminders in the list which have been marked completed.
Reminders in the list which are NOT completed.
All reminders in the list.
The name of the list.
Create a new Reminder object in this list
Save changes to the list.
Returns the system default reminder list configured for new reminders.
Searches for a reminder lists matching the title. If none is found, return undefined.
Searches for a list in the reminders app matching the title. If none is found, creates a new list with that title. If more than one list with the same name exist in Reminders, the first found will be returned.
Get an array all known reminder lists on the device.
Generated using TypeDoc
Reminder objects represent individual tasks in a list in the built-in Reminders app. For examples, see ReminderList documentation.
The alarms assigned to the reminder, if any.
Completion date of the reminder. This value is set automatically when the isCompleted
property is set to true. Setting this property to nil
will set isCompleted
to false.
Due date of the reminder
Does the dueDate property include an assigned time. If false, assignments to the dueDate
property will ignore time components, making the reminder due on a specific date without a time assigned.
Returns true if the reminder has any alarms.
Unique identifier for the reminder.
Flag indicating if the task has been completed.
The list which this task resides in.
Location of the event.
Notes associated with the event.
Integer number representing priority. Assign values matching those Apple uses as follows:
0
: No priority1
: High5
: Medium9
: LowStart date of the reminder
Does the startDate property include an assigned time. If false, assignments to the startDate
property will ignore time components, making the reminder start on a specific date without a time assigned.
The title of the event.
Add an alarm object to the reminder. Be sure to update()
to save after adding alarms. Return true
if the alarm was successfully added. Note that reminders only support alarms created with the Alarm.alarmWithDate
method.
Remove any assigned alarms from the reminder.
Save the task. Returns true if the task is successfully saved in Reminders.
Generated using TypeDoc
Script integration with Microsoft To Do. This object handles OAuth authentication and request signing. The entire Microsoft To Do Graph API can be used with the request
method, and convenience methods are provided for common API endpoints to manage tasks and lists.
Working with the return values and parameters for these methods requires an understanding of the JSON objects created and returned by the API, so refer to type specifications in the API Reference for details on values supported in task and lists. Specifically, review the supported properties of the Task and TaskList objects to understand the values included in fetched objects, and to make modifications.
If an API calls fails, typically the result will be an undefined
value, and the lastError
property will contains error detail information for troubleshooting.
See Examples-Microsoft To Do action group in the Drafts Directory. It contains several example scripted actions.
// create MicrosoftToDo object
let todo = MicrosoftToDo.create();
// create task in "Test" list
let list = todo.findList("Test");
// create task object, more properties available, see API docs
let task = {
"title": `Task Title`,
"importance": "high",
"body": {
"content": "Notes for the task",
"contentType": "text"
};
"dueDateTime": {
"dateTime": Date.today().addDays(1).toISOString(),
"timeZone": "UTC"
}
};
let t = todo.createTask(list, task);
Create new instance.
If a function fails, this property will contain the last error as a string message, otherwise it will be undefined
.
If a function succeeds, this property will contain the last response returned by the To Do API. The JSON returned by the API will be parsed to an object and placed in this property. Refer to To Do API documentation for details on the contents of this object based on call made.
Create new linked resource for a task. A linked resource is a reference to content in an external system, such as a link back to a draft. API documentation
Create list by name.
Get specific list by name. This is a convenience method which will fetch lists and return the first one found with a matching name.
Get all lists. API documentation
Execute a request against the Microsoft To Do API. For successful requests, the HTTPResponse object will contain an object or array or objects decoded from the JSON returned by the API as appropriate to the request made. Refer to API documentation for details about the expected parameters and responses. Drafts will handle wrapping the request in the appropriate OAuth authentication flow.
Requests should only be made to endpoints in the Microsoft Graph API which require the Task.ReadWrite
authentication scope.
an object configuring the request.
A JavaScript object containing data to be encoded into the HTTP body of the request.
An object contain key-values to be added as custom headers in the request. There is no need to provide authorization headers, Drafts will add those.
The HTTP method, like "GET", "POST", "PATCH", etc.
An object containing key-values to be added to the request as URL parameters.
The full URL to the endpoint in the To Do API.
Creates a new MicrosoftToDo object.
Optional string value used to identify a To Do account. Typically this can be omitted if you only work with one To Do account in Drafts. Each unique identifier used for To Do accounts will share credentials - across both action steps and scripts.
Create new task in the specified list. API documentation
Get a specific task by ID. API documentation
Get tasks in a list. API documentation
Update an existing task. Typical usage would be to modify the contents of a task returned by getTask
or getTasks
and sending the modified version as an update API documentation
Generated using TypeDoc
Script integration with WordPress sites via the WordPress XML-RPC API. Currently this object has one runMethod function which can be used to call any method available in the XML-RPC interface.
The WordPress API offers access to a wide variety of functions, including posting, but also retrieving information about categories and tags, or reading posts contents.
Drafts WordPress
object simplifies working with the XML-RPC interface by accepting input parameters as Javascript objects and converting them to the require XML to make requests of the WordPress site. Similarly, it converts to XML returned by WordPress to Javascript objects. Otherwise it is an exact passthrough, so the WordPress API reference should be used to determine method names (e.g. wp.newPost
, wp.getTaxonomies
) available, the appropriate parameters to send.
The WordPress XML-RPC API authenticates via username and password, so it is highly recommended you interact only over HTTPS secure connections, and use Credential
objects to store host/username/password values, rather than hard-coding them in actions.
// setup values to use in post
let title = "Title of Post"
let body = "Body of Post"
// create credentials for site
let cred = Credential.createWithHostUsernamePassword("WordPress", "WordPress * credentials. Include full URL (with http://) of the home page of your WordPress * site in the host field.");
cred.authorize();
// create WordPress object and make request
let wp = WordPress.create(cred.getValue("host"), 1, "", "");
let method = "wp.newPost"
let params = [
1, // blog_id, in most cases just use 1
cred.getValue("username"),
cred.getValue("password"),
{
"post_title": title,
"post_content": body,
"post_status": "draft",
"terms_names" : { // assign categories and tags
"category" : ["Cat1", "BAD"],
"post_tag" : ["Test1", "NOT-TAG"]
}
}
];
let response = wp.runMethod(method, params);
if (response.success) {
let params = response.params;
console.log("Create WordPress post id: " + params[0]);
}
else {
console.log("HTTP Status: " + response.statusCode);
console.log("Fault: " + response.error);
context.fail();
}
Create new instance
This should be the full URL to the home page of the WordPress site. e.g. https://mysite.com
or https://mysite.com/blog/
.
For most WordPress installations, use 1
.
Username to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.
Password to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.
Run an XML-RPC API method on a WordPress site. Any method name supported by the WordPress XML-RPC API can be used, as long as the authentication information provided has appropriate permissions on the site.
The method name as documented in the WordPress XML-RPC API, for example wp.newPost
to create a new post.
Parameters should be a Javascript array of parameters for the method being used. These vary depending on the method and should follow the documentation provided by WordPress.
Create new instance
This should be the full URL to the home page of the WordPress site. e.g. https://mysite.com
or https://mysite.com/blog/
.
For most WordPress installations, use 1
.
Username to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.
Password to login to the WordPress site. Optional if only using runMethod, as credentials will be required directly in parameters for those calls.
Generated using TypeDoc
Represents a Things check list item, which can be added to a Todo. See TJSContainer documentation for details on making requests to Things.
Generated using TypeDoc
The HTTP and HTTPResponse objects are used to run synchronous HTTP requests to communicate with APIs, or just read pages from the web. A full set of custom settings can be passed, and all HTTP methods (GET, POST, PUT, DELETE, etc.) are supported.
var http = HTTP.create(); // create HTTP object
var response = http.request({
"url": "http://myurl.com/api",
"method": "POST",
"data": {
"key":"value"
},
"headers": {
"HeaderName": "HeaderValue"
}
});
if (response.success) {
var text = response.responseText;
var data = response.responseData;
}
else {
console.log(response.statusCode);
console.log(response.error);
}
Create new instance.
An object configuring the request.
An object containing data to be encoded into the HTTP body of the request.
Format to encode data
in the body of request.
An object contain key-values to be added as custom headers in the request.
The HTTP method, like "GET", "POST", etc.
Query parameters to merge with the url. Query parameters can also be part of the original url value.
A password to encode for Basic Authentication.
The absolute HTTP URL for the request.
A username to encode for Basic Authentication.
Instantiate an HTTP
object.
Generated using TypeDoc
Represents a Syntax definition available in the current installation of Drafts.
let syntax = Syntax.find("builtIn", "Markdown");
draft.syntax = syntax;
draft.update();
URL which can be used to install this Syntax in another installation of Drafts. Useful for sharing and backups.
The name of the syntax definition.
The type (builtIn, custom, file) of the syntax definition.
Search for a syntax definition matching the type and name passed and return it if found. Returns undefined if not found.
Get list of all available syntaxes.
Generated using TypeDoc
Represents a Workspace. Can be used to inquire and load workspaces and apply them using methods on the App object.
// find workspace and load it in drafts list
let workspace = Workspace.find("Projects");
app.applyWorkspace(workspace);
Create new instance.
Should flagged drafts be included in archive.
Should flagged drafts be included in inbox.
Action group to load in Action Bar when applying the workspace.
Action group to load in action list when applying the workspace.
Folder tab to select when applying the workspace.
Preferred dark theme to load when applying the workspace.
Preferred light theme to load when applying the workspace.
Show date information in list.
Show last logged action for draft in list.
Show preview of draft body in list.
Show draft tags in list.
A QueryDate specifying a date which all drafts in the workspace must be less than or equal to.
Search string to filter results.
A QueryDate specifying a date which all drafts in the workspace must be greater than or equal to.
Comma-delimited list tag string like "blue, !green" using "!" to omit a tag.
If true
, all (AND) tags in the tag filter must match, if false
match any of the tags (OR)
URL which can be used to install this Workspace in another installation of Drafts. Useful for sharing and backups.
The n
Bookmark
Bookmark objects are used to work with folder bookmarks and the FileManager object to provide access to folders outside the Drafts App Sandbox. Bookmarks are unique by name. A user-friendly name should be used, as the first time a bookmark is required, the user is prompted to select the folder in their file system to associate with the bookmark, and a useful name can help guide them to selecting the correct folder.
Learn more about Bookmarks in the User Guide
Example
// find or create a named Bookmark let bookmark = Bookmark.findOrCreate("My-Folder"); let fm = FileManager.createForBookmark(bookmark);
// write to a file at the root of the bookmark folder let success = fm.writeString("/ScriptedFile.txt", "This is the file * content");
// read from file in bookmarked folder let content = fm.readString("/Test Folder/Test.txt")