hs.pasteboard
ModuleModule for interacting with the macOS pasteboard (clipboard)
The macOS pasteboard is "rich" — a single clipboard operation can carry multiple representations of the same content for different applications to consume. For example, text copied from a web browser may carry plain text, HTML, and RTF representations simultaneously.
Basic Usage
// Read and write plain text
const text = hs.pasteboard.readString()
hs.pasteboard.writeString("Hello from Hammerspoon!")
// Check what types are currently on the pasteboard
const available = hs.pasteboard.types()
// Write multiple representations at once
hs.pasteboard.writeObjects({
"public.utf8-plain-text": "Hello",
"public.html": "<b>Hello</b>"
})
// Watch for pasteboard changes
const handler = (changeCount) => {
console.log("Pasteboard changed, count:", changeCount)
console.log("New text:", hs.pasteboard.readString())
}
hs.pasteboard.on("change", handler)
// Later: hs.pasteboard.off("change", handler)
Pasteboard Conventions (nspasteboard.org)
macOS has no built-in notification API for transient or confidential clipboard content, so a
community convention has emerged (see nspasteboard.org) around four
org.nspasteboard.* UTI marker types. These markers carry no payload — their mere presence on
the pasteboard signals intent to other applications.
Standard marker UTIs
| UTI | Meaning |
|---|---|
org.nspasteboard.TransientType |
Content is temporary; it will be removed or overwritten shortly. Clipboard historians should not record this change. |
org.nspasteboard.ConcealedType |
Content is sensitive (e.g. a password). Historians should obfuscate it if displayed and ideally encrypt it if stored. |
org.nspasteboard.AutoGeneratedType |
Content was placed by an application without any user Copy action. Historians should generally skip recording it. |
org.nspasteboard.source |
The bundle identifier of the application that placed the content. Use an empty string when the source is unknown. |
Legacy proprietary markers
Several apps defined their own markers before the org.nspasteboard.* standard existed.
Clipboard historians should also honour these for compatibility:
| UTI | Application |
|---|---|
de.petermaurer.TransientPasteboardType |
TextExpander, Butler |
com.typeit4me.clipping |
TypeIt4Me |
Pasteboard generator type |
Typinator |
com.agilebits.onepassword |
1Password (confidential) |
com.apple.is-remote-clipboard |
macOS (remote content) |
For scripts that write to the pasteboard
If your script temporarily commandeers the pasteboard (e.g. to trigger a paste), add
org.nspasteboard.TransientType so clipboard historians skip the entry:
hs.pasteboard.writeObjects({
"public.utf8-plain-text": "temporary value",
"org.nspasteboard.TransientType": ""
})
For sensitive content such as a generated password, use org.nspasteboard.ConcealedType:
hs.pasteboard.writeObjects({
"public.utf8-plain-text": "s3cr3t!",
"org.nspasteboard.ConcealedType": ""
})
For scripts that monitor the pasteboard
If you are building a clipboard history tool with on, skip or obfuscate entries that
carry any of the marker UTIs listed above:
const SKIP_TYPES = [
"org.nspasteboard.TransientType",
"org.nspasteboard.AutoGeneratedType",
"de.petermaurer.TransientPasteboardType",
"com.typeit4me.clipping",
"Pasteboard generator type",
]
const CONCEAL_TYPES = [
"org.nspasteboard.ConcealedType",
"com.agilebits.onepassword",
]
hs.pasteboard.on("change", (changeCount) => {
const types = hs.pasteboard.types()
if (SKIP_TYPES.some(t => types.includes(t))) return // ignore transient
const conceal = CONCEAL_TYPES.some(t => types.includes(t)) // handle sensitively
// … record or display the pasteboard contents …
})
Event Types
The events this module's watchers emit, and when. In TypeScript, each type is a union of its event names that you can use as a type of your own:
HSPasteboardEvent
An event name for hs.pasteboard.on(), hs.pasteboard.off() and hs.pasteboard.once()
| Event | Description |
|---|---|
"change" |
The pasteboard's contents changed |
Properties
hs.pasteboard.changeCount
The pasteboard change count. Increments each time any application writes to the pasteboard. Comparing a saved value to the current value is the standard way to detect external changes.
hs.pasteboard.watcherInterval
The polling interval for the pasteboard watcher, in seconds. Defaults to 0.5. Changes take effect the next time a watcher is started (i.e. after removing and re-adding).
Methods
hs.pasteboard.readString() -> string
Read plain text from the pasteboard
hs.pasteboard.readString() -> string
const text = hs.pasteboard.readString()
hs.pasteboard.readHTML() -> string
Read HTML from the pasteboard
hs.pasteboard.readHTML() -> string
const html = hs.pasteboard.readHTML()
hs.pasteboard.readRTF() -> string
Read RTF from the pasteboard
hs.pasteboard.readRTF() -> string
const rtf = hs.pasteboard.readRTF()
hs.pasteboard.readURL() -> string
Read a URL from the pasteboard
If several URLs are on the pasteboard, this returns the first; use readURLs() for all of them.
As with readURLs(), file-reference URLs (file:///.file/id=...) are resolved to file-path
URLs (file:///...) when possible.
hs.pasteboard.readURL() -> string
const url = hs.pasteboard.readURL()
hs.pasteboard.readURLs() -> string[]
Read all URLs from the pasteboard (for example, multiple files copied in Finder).
File-reference URLs (file:///.file/id=...) are resolved to standard file-path URLs
(file:///...) when possible.
hs.pasteboard.readURLs() -> string[]
const urls = hs.pasteboard.readURLs()
console.log("Copied " + urls.length + " URLs")
hs.pasteboard.readImage() -> HSImage
Read an image from the pasteboard
hs.pasteboard.readImage() -> HSImage
const img = hs.pasteboard.readImage()
hs.pasteboard.readData(uti) -> string
Read raw data for a specific UTI type, returned as a base64-encoded string. Use this for types not covered by the convenience read methods.
hs.pasteboard.readData(uti) -> string
| Name | Type | Description |
|---|---|---|
| uti | string | A UTI type string (e.g. "com.adobe.pdf") |
const b64 = hs.pasteboard.readData("com.adobe.pdf")
hs.pasteboard.readBytes(uti) -> Uint8Array | null
Read raw bytes for a specific UTI type as a Uint8Array.
This is the binary counterpart to readData(), avoiding base64 encoding overhead when
working with images, PDFs, or SQLite BLOBs.
hs.pasteboard.readBytes(uti) -> Uint8Array | null
| Name | Type | Description |
|---|---|---|
| uti | string | A UTI type string (e.g. "public.png", "com.adobe.pdf") |
const pngBytes = hs.pasteboard.readBytes("public.png")
if (pngBytes) console.log("Read " + pngBytes.length + " bytes")
hs.pasteboard.readItems(options) -> Array<Record<string, Uint8Array>>
Read all items currently on the pasteboard with their UTI representations as Uint8Arrays.
Unlike the single-value readers, this preserves per-item boundaries (for example, multiple
files copied in Finder appear as separate objects in the returned array, each carrying its
own "public.file-url" payload).
Reading every representation can be slow and use a lot of memory: apps often provide some
formats only on request, so reading them makes the app that copied the data produce each one.
Pass options.types to read only the UTIs you need, skipping large or unwanted
representations (such as "com.apple.webarchive" or dynamic "dyn.*" types).
Items with none of the requested types are left out of the returned array. If options is an
array, or options.types isn't an array of strings, nothing is read and a warning is logged to
the Console; unknown options are ignored with a warning.
hs.pasteboard.readItems(options) -> Array<Record<string, Uint8Array>>
| Name | Type | Description |
|---|---|---|
| options optional | object | null | Which representations to read |
| types optional | string[] | The UTIs to read. When omitted, every UTI on every item is read. |
// Skip webarchives and dynamic types by filtering types() first
const wanted = hs.pasteboard.types().filter(t => t !== "com.apple.webarchive" && !t.startsWith("dyn."))
const items = hs.pasteboard.readItems({ types: wanted })
// Read everything on the pasteboard
const allItems = hs.pasteboard.readItems()
hs.pasteboard.writeString(str) -> boolean
Write plain text to the pasteboard, replacing all current contents
hs.pasteboard.writeString(str) -> boolean
| Name | Type | Description |
|---|---|---|
| str | string | The text string to write |
hs.pasteboard.writeString("Hello, world!")
hs.pasteboard.writeHTML(html) -> boolean
Write HTML to the pasteboard, replacing all current contents
hs.pasteboard.writeHTML(html) -> boolean
| Name | Type | Description |
|---|---|---|
| html | string | The HTML string to write |
hs.pasteboard.writeHTML("<b>Hello</b>")
hs.pasteboard.writeRTF(rtf) -> boolean
Write RTF to the pasteboard, replacing all current contents
hs.pasteboard.writeRTF(rtf) -> boolean
| Name | Type | Description |
|---|---|---|
| rtf | string | The RTF string to write |
hs.pasteboard.writeRTF(rtfString)
hs.pasteboard.writeURL(url) -> boolean
Write a URL to the pasteboard, replacing all current contents
hs.pasteboard.writeURL(url) -> boolean
| Name | Type | Description |
|---|---|---|
| url | string | The URL string to write |
hs.pasteboard.writeURL("https://www.example.com")
hs.pasteboard.writeURLs(urls) -> boolean
Write one or more URLs to the pasteboard atomically, replacing all current contents.
Writing file URLs via writeURLs() uses AppKit's NSURL pasteboard representation so
Finder and other apps receive proper file references and sandbox extensions when pasting
multiple copied files.
hs.pasteboard.writeURLs(urls) -> boolean
| Name | Type | Description |
|---|---|---|
| urls | string[] | Array of URL strings (each must have a scheme, e.g. "file:///..." or "https://...") |
hs.pasteboard.writeURLs(["file:///tmp/a.txt", "file:///tmp/b.txt"])
hs.pasteboard.writeImage(image) -> boolean
Write an image to the pasteboard, replacing all current contents
hs.pasteboard.writeImage(image) -> boolean
| Name | Type | Description |
|---|---|---|
| image | HSImage | An HSImage to write |
const img = hs.pasteboard.readImage()
hs.pasteboard.writeImage(img)
hs.pasteboard.writeData(base64, uti) -> boolean
Write raw base64-encoded data for a specific UTI type, replacing all current contents. Use this for types not covered by the convenience write methods.
hs.pasteboard.writeData(base64, uti) -> boolean
| Name | Type | Description |
|---|---|---|
| base64 | string | The data encoded as a base64 string |
| uti | string | A UTI type string (e.g. "com.adobe.pdf") |
hs.pasteboard.writeData(b64Encoded, "com.adobe.pdf")
hs.pasteboard.writeBytes(bytes, uti) -> boolean
Write raw bytes for a specific UTI type, replacing all current contents.
This is the binary counterpart to writeData(), accepting a Uint8Array, any other typed
array, or an ArrayBuffer.
hs.pasteboard.writeBytes(bytes, uti) -> boolean
| Name | Type | Description |
|---|---|---|
| bytes | Uint8Array | ArrayBuffer | The raw bytes to write |
| uti | string | A UTI type string (e.g. "public.png", "com.adobe.pdf") |
const bytes = hs.pasteboard.readBytes("public.png")
if (bytes) hs.pasteboard.writeBytes(bytes, "public.png")
hs.pasteboard.writeObjects(representations) -> boolean
Write multiple type representations for a single item to the pasteboard atomically, replacing all current contents.
Keys must be UTI type strings; values may be strings or binary data (Uint8Array, typed
array, or ArrayBuffer). This is how you provide both a plain-text fallback and richer or
binary representations in a single clipboard operation. Values of any other type are skipped,
with a warning in the Console.
hs.pasteboard.writeObjects(representations) -> boolean
| Name | Type | Description |
|---|---|---|
| representations | Record<string, string | Uint8Array | ArrayBuffer> | A JavaScript object mapping UTI strings to strings or raw bytes |
hs.pasteboard.writeObjects({
"public.utf8-plain-text": "Hello",
"public.html": "<b>Hello</b>"
})
hs.pasteboard.writeItems(items) -> boolean
Write one or more pasteboard items atomically, replacing all current contents.
Each element of items is an object mapping UTI type strings to either strings or binary
data (Uint8Array, typed array, or ArrayBuffer), matching the shape returned by
readItems(). Use this to restore multi-item clipboard contents (such as multiple copied
files) or arbitrary multi-UTI binary payloads without losing fidelity.
An item whose only key is "public.file-url" is written as a file URL, the same way
writeURLs() writes it. Items with other representations as well are written as raw data.
Either way, sandboxed apps that paste a "public.file-url" can open the file, so a Finder
copy saved with readItems() can be restored with writeItems() and pasted as files.
If any item isn't an object with at least one string or binary value, nothing is written. Within an item, values that aren't strings or binary data are skipped, with a warning in the Console.
hs.pasteboard.writeItems(items) -> boolean
| Name | Type | Description |
|---|---|---|
| items | Array<Record<string, string | Uint8Array | ArrayBuffer>> | Array of item objects mapping UTI strings to strings or raw bytes |
const saved = hs.pasteboard.readItems()
// ... later ...
hs.pasteboard.writeItems(saved)
hs.pasteboard.types() -> string[]
Get all UTI type strings currently on the pasteboard, across all items
hs.pasteboard.types() -> string[]
const types = hs.pasteboard.types()
hs.pasteboard.hasType(uti) -> boolean
Check whether a specific UTI type is currently available on the pasteboard
hs.pasteboard.hasType(uti) -> boolean
| Name | Type | Description |
|---|---|---|
| uti | string | A UTI type string to check for |
if (hs.pasteboard.hasType("public.html")) console.log("HTML available")
hs.pasteboard.clear() -> None
Clear all contents from the pasteboard
hs.pasteboard.clear() -> None
hs.pasteboard.clear()
hs.pasteboard.on(event, listener) -> None
Register a listener that fires whenever the pasteboard contents change.
Because macOS provides no pasteboard change notification API, this is implemented by
polling changeCount at the interval specified by watcherInterval.
hs.pasteboard.on(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSPasteboardEvent | The event to listen for (the only event this module emits) |
| listener | (changeCount: number) => void | Called with the new changeCount whenever the pasteboard changes |
| Event | Description |
|---|---|
"change" |
The pasteboard's contents changed |
try {
hs.pasteboard.on('change', count => console.log("Pasteboard changed:", count))
} catch (err) {
console.error(err.message)
}
hs.pasteboard.off(event, listener) -> None
Remove a previously registered pasteboard change listener.
hs.pasteboard.off(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSPasteboardEvent | The event the listener was registered for |
| listener | (changeCount: number) => void | The function originally passed to on |
| Event | Description |
|---|---|
"change" |
The pasteboard's contents changed |
const onChange = count => console.log(count)
hs.pasteboard.on('change', onChange)
// later…
hs.pasteboard.off('change', onChange)
hs.pasteboard.once(event, listener) -> None
Register a listener that fires at most once, the next time the pasteboard contents change.
hs.pasteboard.once(event, listener) -> None
| Name | Type | Description |
|---|---|---|
| event | HSPasteboardEvent | The event to listen for |
| listener | (changeCount: number) => void | Called once, then automatically removed |
| Event | Description |
|---|---|
"change" |
The pasteboard's contents changed |
try {
hs.pasteboard.once('change', count => console.log("First change:", count))
} catch (err) {
console.error(err.message)
}