PopClip JavaScript API Reference
    Preparing search index...

    Interface PopClip

    This interface describes the methods and properties of the global popclip object.

    interface PopClip {
        appear(): void;
        context: Context;
        copyContent(
            content: PasteboardContent,
            options?: CopyOptions,
        ): Promise<void>;
        copyText(text: string, options?: CopyOptions): Promise<void>;
        input: Input;
        modifiers: Modifiers;
        openTemplateUrl(
            urlTemplate: string,
            query: string,
            options?: {
                activate?: boolean;
                app?: string;
                backgroundTab?: boolean;
                clean?: boolean;
                copy?: boolean;
                options?: { [key: string]: string };
                plus?: boolean;
                verbatim?: boolean;
            },
        ): Promise<void>;
        openUrl(
            url: string | URL,
            options?: { activate?: boolean; app?: string; backgroundTab?: boolean },
        ): Promise<void>;
        options: Options & AuthOptions;
        pasteContent(
            content: PasteboardContent,
            options?: PasteOptions,
        ): Promise<void>;
        pasteText(text: string, options?: PasteOptions): Promise<void>;
        performCommand(
            command: "cut" | "copy" | "paste",
            options?: { transform?: "none" | "plain" },
        ): Promise<void>;
        pressKey(
            key: string | number,
            modifiers?: number,
            options?: { target?: "session" | "app" | "hid" },
        ): Promise<void>;
        pressKeys(
            sequence: (string | number)[],
            options?: { target?: "session" | "app" | "hid" },
        ): Promise<void>;
        revealFile(path: string): void;
        runAppleScript(
            source: string,
            options?: AppleScriptOptions,
        ): Promise<AppleScriptResult>;
        runAppleScriptFile(
            path: string,
            options?: AppleScriptOptions,
        ): Promise<AppleScriptResult>;
        runShortcut(
            name: string,
            options?: { input?: string },
        ): Promise<AppleScriptResult>;
        settingsRequiredError(message?: string): Error;
        share(
            serviceName: string,
            items: (string | URL | RichString | { url: string })[],
        ): Promise<void>;
        showFailure(): void;
        showSettings(): void;
        showSuccess(): void;
        showText(
            text: string,
            options?: { preview?: boolean; style?: "compact" | "large" },
        ): void;
        signInRequiredError(message?: string): Error;
    }
    Index
    context: Context

    The current context.

    input: Input

    The current selection.

    modifiers: Modifiers

    The state of the modifier keys when the action was invoked in PopClip.

    During the execution of the population function, all the modifiers will read as false.

    options: Options & AuthOptions

    The current values of the options.

    • Trigger PopClip to appear again with the current selection.

      Returns void

    • Place the given string on the pasteboard, optionally showing "Copied" notification to the user.

      Returns a promise that resolves once the items are committed to the pasteboard, and rejects if the pasteboard refuses the write.

      Parameters

      • text: string

        The plain text string to copy

      • Optionaloptions: CopyOptions

      Returns Promise<void>

    • Fill a query into a template URL and open it. This is the mechanism used by URL actions, exposed to JavaScript.

      The query is trimmed of surrounding whitespace and URL-encoded, then substituted into the template in place of the placeholders *** and {popclip text}. Any {popclip option <name>} placeholders are replaced with the URL-encoded values supplied in the options sub-dictionary. The resulting URL is then opened as by openUrl, and that open's promise is returned.

      When the copy option is set, the query text is also copied to the clipboard.

      Parameters

      • urlTemplate: string

        The URL template containing placeholders.

      • query: string

        The text to substitute into the template's query placeholders.

      • Optionaloptions: {
            activate?: boolean;
            app?: string;
            backgroundTab?: boolean;
            clean?: boolean;
            copy?: boolean;
            options?: { [key: string]: string };
            plus?: boolean;
            verbatim?: boolean;
        }

        Options.

        • Optionalactivate?: boolean

          Whether to request that macOS activate the target app. (Default: true)

        • Optionalapp?: string

          Bundle identifier of the app to open the URL with. For example "com.google.Chrome".

        • OptionalbackgroundTab?: boolean

          When opening a web URL in a supported browser, whether to open the URL in a background tab. (Default: false)

        • Optionalclean?: boolean

          Collapse runs of internal whitespace in the query to a single space. Mirrors the clean query property of URL actions. (Default: false)

        • Optionalcopy?: boolean

          Whether to copy the query text to the clipboard, overriding the app's default behaviour for this call.

        • Optionaloptions?: { [key: string]: string }

          A mapping of option names to values, used to fill any {popclip option <name>} placeholders in the template.

        • Optionalplus?: boolean

          Encode spaces in the query as + instead of %20. Some search engines (for example Amazon) expect this format. Mirrors the spaces as plus property of URL actions. (Default: false)

        • Optionalverbatim?: boolean

          Wrap the query in double quotes for an exact-phrase search. If unspecified, defaults to the state of the Option (⌥) key when the action was invoked.

      Returns Promise<void>

      popclip.openTemplateUrl("https://www.google.com/search?q=***", popclip.input.text);
      
    • Open a URL in a browser or other application.

      If a target application bundle identifier is specified via the app option, PopClip will ask that app to open the URL.

      If no target app is specified:

      • If the URL is a web URL (http or https scheme) and the current app is a browser, the URL is opened in the current app.
      • Otherwise, PopClip asks macOS to open the URL in the default handler for its scheme.

      Any parameters etc. in the URL must be appropriately percent-encoded. JavaScript provides the encodeURIComponent() function for this. Alternatively you can use the URL class, which is available as a global in PopClip's JavaScript environment. When a URL instance is passed, any + characters in it are first replaced with %20: a query built with URLSearchParams encodes spaces as + (form encoding), which not every receiver interprets as a space, whereas %20 is unambiguous.

      Returns a promise that resolves once the request has been delivered to the browser or OS.

      Parameters

      • url: string | URL

        The URL to open: a string, used exactly as given, or a URL instance.

      • Optionaloptions: { activate?: boolean; app?: string; backgroundTab?: boolean }

        Options.

        • Optionalactivate?: boolean

          Whether to request that macOS activate the target app. (Default: true)

        • Optionalapp?: string

          Bundle identifier of the app to open the URL with. For example "com.google.Chrome".

        • OptionalbackgroundTab?: boolean

          When opening a web URL in a supported browser, whether to open the URL in a background tab. (Default: false)

      Returns Promise<void>

      // examples using string URLs
      popclip.openUrl("https://xkcd.com"); // open in current/default browser
      popclip.openUrl("https://xkcd.com", {app: "com.brave.Browser"}); // open in Brave browser

      // example using URL class
      const mailUrl=new URL("mailto:support@pilotmoon.com");
      mailUrl.searchParams.append("subject", "What's up?");
      popclip.openUrl(mailUrl); // the mailto: link will open in the default mail application
    • If the target app's Paste command is available, this method places the given string on the pasteboard and then invokes the target app's Paste command. If the restore flag is set in the options, it will then restore the original pasteboard contents.

      If the target app's Paste command is not available, it behaves as copyText instead.

      Returns a promise that resolves once the paste command has been delivered to the app, after the pasteboard write was confirmed and — if restore is set — after the pasteboard was restored. It rejects if the write never appears on the pasteboard or the restore fails.

      Parameters

      • text: string

        The plain text string to paste

      • Optionaloptions: PasteOptions

      Returns Promise<void>

      // place "Hello" on the clipboard and invoke Paste
      await popclip.pasteText("Hello");
      // place "Hello", then restore the original pasteboard contents
      await popclip.pasteText("Hello", {restore: true});
    • Invokes a command in the target app.

      Returns a promise. For cut and copy it resolves once the app has placed the resulting content on the pasteboard and any transform has been applied. For paste it resolves once the command has been delivered to the app. An unknown command or transform value throws immediately, doing nothing.

      Parameters

      • command: "cut" | "copy" | "paste"

        Either cut, copy or paste.

      • Optionaloptions: { transform?: "none" | "plain" }

        Options for the command.

        • Optionaltransform?: "none" | "plain"

          Transformation to apply to the pasteboard contents. (Default: none)

          • none: regular pasteboard operation
          • plain: strips away everything but plain text

      Returns Promise<void>

      await popclip.performCommand("copy")
      
    • Simulate a key press by the user.

      Some key code and modifier constants are available in util.constant.

      To press a sequence of combos, with waits between them if needed, see pressKeys().

      Parameters

      • key: string | number

        The key to press. When this parameter is a string, PopClip will interpret it as in Key Press actions. When this parameter is a number, PopClip will use that exact key code.

      • Optionalmodifiers: number

        An optional bit mask specifying additional modifier keys, if any.

      • Optionaloptions: { target?: "session" | "app" | "hid" }

        Options for the key press.

        The target option says where PopClip posts the key events:

        • session (the default) posts to the session event tap, kCGSessionEventTap.
        • app posts to the process of the application PopClip is acting on, using CGEventPostToPid(). This is the only target aimed at a particular process, so the keys arrive there whatever holds keyboard focus at the time.
        • hid posts to the HID event tap, kCGHIDEventTap.

        Where the events go from a tap is up to the system. If a key combo does not have the effect you expect with one target, it is worth trying the others.

      Returns Promise<void>

      A promise that resolves once the press has been made, and rejects if it fails. Await it when a later step depends on the press completing.

      // press the key combo ⌘B
      await popclip.pressKey('command B');
      // press the key combo ⌥⌘H
      await popclip.pressKey('option command H');
      // press the return key
      await popclip.pressKey('return');
      await popclip.pressKey(util.constant.KEY_RETURN); // equivalent
      // press option and the page down key
      await popclip.pressKey('option 0x79');
      await popclip.pressKey(0x79, util.constant.MODIFIER_OPTION); // equivalent
      await popclip.pressKey('command c');
      popclip.pressKey('command space', 0, { target: 'hid' });
    • Simulate a sequence of key presses, with optional waits between them.

      The sequence runs as one unit: PopClip makes the presses in order on its key-press queue, and no other press can interleave mid-sequence.

      Parameters

      • sequence: (string | number)[]

        The presses to make, in order. Each entry is a key press in the same form as pressKey()'s key parameter — a string such as 'command b' or a numeric key code — or a wait, written 'wait <milliseconds>' (up to 5000). If any entry does not parse, the call throws and nothing is pressed.

      • Optionaloptions: { target?: "session" | "app" | "hid" }

        The same options as pressKey(): target says where the presses are posted (session, the default, or app or hid).

      Returns Promise<void>

      A promise that resolves once the whole sequence has run, and rejects if the presses could not be made.

      // press ⌘space, give Spotlight a moment, then paste
      await popclip.pressKeys(['command space', 'wait 100', 'command v'], { target: 'hid' });
    • Show a file or folder in the Finder. A file is selected inside its enclosing folder; a folder is opened as the window's own root.

      The path must be an absolute path on the user's disk — the kind found in popclip.input.data.paths.

      Throws if the path is omitted or does not exist.

      Parameters

      • path: string

        An absolute path to an existing file or folder. A leading ~ is expanded to the user's home folder.

      Returns void

      popclip.revealFile(popclip.input.data.paths[0]);
      popclip.revealFile("~/Downloads");
    • Run an AppleScript, supplied as source text.

      Requires the script entitlement, and may only be called during the action phase.

      To call a specific handler (subroutine) in the script, name it in the options — see AppleScriptOptions.

      Bad input throws immediately, and nothing runs. A script that runs and errors rejects the promise with an error carrying the AppleScript error number as its errorNumber property.

      Parameters

      Returns Promise<AppleScriptResult>

      A promise for the script's return value — see AppleScriptResult.

      const script = `
      on addReminder(theName)
      tell application id "com.apple.reminders"
      make new reminder with properties {name:theName}
      end tell
      end addReminder`;
      await popclip.runAppleScript(script, {
      handler: "addReminder",
      parameters: [popclip.input.text],
      permissions: ["reminders"],
      });
    • Run an AppleScript from a file in the extension package.

      The same as runAppleScript() in every way except where the script comes from: path names a script file inside the package, relative to the package root. An .applescript file is read as source text; an .scpt (compiled script) file is opened by the script runner directly. Other file types, and paths outside the package, are refused.

      Parameters

      Returns Promise<AppleScriptResult>

      A promise for the script's return value — see AppleScriptResult.

      const result = await popclip.runAppleScriptFile("scripts/lookup.applescript", {
      handler: "lookup",
      parameters: [popclip.input.text],
      });
    • Run a shortcut from the user's Shortcuts library, by name.

      May only be called during the action phase.

      Bad input (a missing name, a non-string input) throws immediately, and nothing runs. A shortcut that could not be run, or that errors, rejects the promise.

      Parameters

      • name: string

        The name of the shortcut, exactly as it appears in the Shortcuts app.

      • Optionaloptions: { input?: string }

        input: text passed to the shortcut as its input; omitted means none.

      Returns Promise<AppleScriptResult>

      A promise for the shortcut's result — see AppleScriptResult. The result is the shortcut's output: what its last action produces, or what it passes to a "Stop and Output" action. A shortcut that produces no output resolves to undefined.

      const result = await popclip.runShortcut("My Shortcut", { input: popclip.input.text });
      
    • Returns an Error to throw to send the user to the settings UI without clearing the sign-in (for example a required option is missing or invalid).

      Parameters

      • Optionalmessage: string

        Optional message for logs/diagnostics.

      Returns Error

    • Share items with a named macOS sharing service.

      Parameters

      • serviceName: string

        The name of the sharing service to use.

      • items: (string | URL | RichString | { url: string })[]

        An array of items to share. A string is shared as plain text; a RichString as rich text; a URL instance, or an object with a url string property, as a URL. (The { url } form uses the string exactly as given; a URL instance gets the + to %20 replacement described at openUrl.)

      Returns Promise<void>

      // share a string with the Messages service
      popclip.share("com.apple.share.Messages.window", ["Hello, world!"]);
      // share a URL with the Safari Reading List service
      popclip.share("com.apple.share.System.add-to-safari-reading-list", [new URL("https://example.com")]);
      // share an html string with the Notes service
      const item = new RichString("Some <b>simple</b> html", { format: "html" })
      popclip.share("com.apple.Notes.SharingExtension", [item]);

      The list of available sharing services is determined by the user's system configuration.

      Returns a promise that resolves when the share completes (or when the user cancels the share UI), and rejects if macOS reports that the share failed. The share UI can stay open indefinitely, so only await this if your action needs to wait for the outcome.

      If the service name is not recognized, or if the service cannot handle the supplied items, an error is thrown.

    • PopClip will show an "X" symbol to indicate failure.

      Returns void

    • PopClip will open the settings UI for this extension.

      If the extension has no settings, this method does nothing.

      Returns void

    • PopClip will show a checkmark symbol to indicate success.

      Returns void

    • Display text to the user.

      Parameters

      • text: string

        The text to display.

      • Optionaloptions: { preview?: boolean; style?: "compact" | "large" }

        Options.

        • Optionalpreview?: boolean

          Applies to compact display mode only. If true, and the app's Paste command is available, the displayed text will be in a clickable button which, when clicked, pastes the full text.

        • Optionalstyle?: "compact" | "large"

          Display style:

          • compact (default): Show the text inside PopClip's popup. It will be truncated to 160 characters when shown.
          • large: Show as "Large Type" in full screen.

      Returns void

    • Returns an Error to throw when the stored sign-in credential is no longer valid (for example the server rejected or revoked the token). PopClip clears the saved secret — so the extension appears signed out — and opens the settings UI to sign in again.

      Parameters

      • Optionalmessage: string

        Optional message for logs/diagnostics.

      Returns Error

      if (isAuthError(e)) throw popclip.signInRequiredError();