Scripting with sketch

My notes on scripting with sketch.


Plugins > Custom Plugin option (ctrl + shift + K). In the Custom Plugin sheet give your plugin a name and hit Save. Sketch will generate all the necessary files and folder structure for you. The plugin will now reside in: ~/Library/Application\ Support/com.bohemiancoding.sketch3/Plugins


var onRun = function(context) {
  var app = [NSApplication sharedApplication];//reference the Application
  var doc = context.document;//reference the Sketch Document
  var pages = [doc pages]; //reference all the pages in the document in an array
  for (var i = 0; i < pages.count(); i++){//loop through the pages of the document
    var page = pages[i]; //reference each page
    var pageName = [page name];//get the name of the page
    log(pageName);//show the page name in the console
  doc.showMessage("MyPlugin Finished!");//show a message at the bottom of Sketch
  [app displayDialog:"This document has "+ pages.count() + "pages." withTitle:"Alert Box Title"];//send an alert message to the application

Basic example:

log('This is an example Sketch script.');
var documentName = context.document.displayName();
log('The current document is named: ' + documentName);
var selectedLayers = context.selection;
var selectedCount = selectedLayers.count();
if (selectedCount == 0) {
  log('No layers are selected.');
} else {
  log('Selected layers:');
  for (var i = 0; i < selectedCount; i++) {
    var layer = selectedLayers[i];
    log((i+1) + '. ' +;


  • You can use the log() function to write to the System Console (MacOS) to see output. This is where you will also see exceptions. Just be sure to search for Sketch in the search bar to filter out other applications, and also your own log keyword, to get only plugin specific log outputs.

  • Force sketch to reload script under development: Terminal: defaults write ~/Library/Preferences/com.bohemiancoding.sketch3.plist AlwaysReloadScript -bool YES

Making the plugin:

  1. Add Manifest.json and Main.js to a folder called Sketch
  2. Add the sketch folder into a new folder named: MyPlugin.sketchplugin. Place this in here: ~/Library/Application\ Support/com.bohemiancoding.sketch3/Plugins/
  3. Fire up sketch and see your plugin in the plugin menu
  4. Start splitting up your code into modules. And then import them by @import 'common.js' Then you are able to organise the code better.

.sketchplugin structure:

└── Contents
    ├── Resources
        └── icon.png
    └── Sketch
        ├── manifest.json
        └── MyClass.js