Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/zotero/zotero-connectors/llms.txt

Use this file to discover all available pages before exploring further.

The Message API is the internal RPC layer that lets injected content scripts call functions implemented in the background (service worker) context, and vice versa. When you call Zotero.Translators.get(...) from a page-injected script, the actual work runs in the background; the messaging layer serializes arguments, routes the call, awaits the result, and deserializes the response — all transparently. You would interact with the MESSAGES registry directly only when extending the connector with a new cross-context call, adding serialization hooks for a custom type, or debugging an unexpected message boundary failure.
The constant MESSAGE_SEPARATOR is defined as ".". Message names are therefore formed as NAMESPACE.METHOD (e.g., Translators.get, Connector.callMethod). In Chrome/Chromium, messages are sent as [messageName, args] arrays through browser.runtime.onMessage; in Safari, the same namespace/method structure is used but transport is handled by safari/messaging_global.js.

MESSAGES Registry Structure

Each entry in the MESSAGES object lives at MESSAGES[NAMESPACE][METHOD]. The value of each method entry controls messaging behavior:
ValueMeaning
trueThe call is made and a response is expected and returned to the caller.
falseFire-and-forget — no response is awaited or returned.
ObjectAdvanced configuration with optional background and inject hook sub-objects (see below).

Hook Object Shape

{
  background: {
    preSend: async function(response) { /* transform response before sending to injected page */ },
    postReceive: async function(args, tab, frameId) { /* transform args after receipt, before calling fn */ },
    minArgs: Number  // pad args array to at least this length before calling
  },
  inject: {
    preSend: async function(args) { /* transform args before sending from injected page */ },
    postReceive: async function(response) { /* transform response after receiving in injected page */ }
  },
  response: false  // optional; set false to make an object-configured entry fire-and-forget
}
When a method value is an object but response is not explicitly set to false, the call still returns a response. Setting response: false on an object entry makes it fire-and-forget even when hooks are configured (see Debug.log).

Namespaces

Manages translator lookup and delivery from the background to injected scripts. Translators are heavy objects; hooks serialize them to plain objects crossing the boundary and reconstruct Zotero.Translator instances on the inject side.
MethodValueNotes
updateFromRemotetrueTriggers a remote translator update; returns when complete.
getObjectReturns a single translator.
getAllForTypeObjectReturns all translators matching a type.
getWebTranslatorsForLocationObjectReturns web translators and proxies for a URL.
getCodeForTranslatorObjectReturns translator code; inject side strips to translatorID before sending.
get hooks:
  • background.preSend — calls Zotero.Translators.serialize(translators, TRANSLATOR_PASSING_PROPERTIES) before the response is sent
  • inject.postReceive — reconstructs a single new Zotero.Translator(translator) from the plain object
getAllForType hooks:
  • background.preSend — serializes the translators array with TRANSLATOR_PASSING_PROPERTIES
  • inject.postReceive — maps each element to new Zotero.Translator(translator)
getWebTranslatorsForLocation hooks:
  • background.preSend — serializes data[0] (translators array) and passes through data[1] (proxies)
  • inject.postReceive — deserializes data[0] to Zotero.Translator objects and data[1] to new Zotero.Proxy objects, returning [translators, proxies]
getCodeForTranslator hooks:
  • inject.preSend — extracts only { translatorID: translator.translatorID } from the full translator argument, reducing payload size
  • background.postReceive — calls Zotero.Translators.getWithoutCode(translatorInfo.translatorID) and returns it as the first argument
// Example: get a translator by ID from an injected script
const translator = await Zotero.Translators.get(translatorID);
// The messaging layer handles serialize → send → reconstruct automatically.
Relay for the Manifest V3 offscreen document, which runs translator sandboxes outside the service worker.
MethodValueNotes
sendMessagetrueForwards a message to the offscreen document; returns the response.
Debug logging and storage control across the background/inject boundary.
MethodValueNotes
gettrueRetrieves the current debug log contents.
bgInitfalseSignals background initialization; fire-and-forget.
clearfalseClears stored debug output; fire-and-forget.
logObjectLogs a debug message; fire-and-forget (response: false).
setStorefalseEnables or disables debug log storage; fire-and-forget.
log configuration:
  • response: false — fire-and-forget despite being an object entry
  • background.minArgs: 4 — the args array is padded to at least 4 elements before the background function is invoked
Methods that communicate with (or about) the Zotero desktop client HTTP server.
MethodValueNotes
checkIsOnlinetruePings Zotero desktop; returns boolean.
callMethodtrueExecutes an HTTP RPC call to the Zotero connector server.
callMethodWithCookiestrueLike callMethod but first collects and attaches browser cookies.
saveSingleFileObjectSaves a SingleFile snapshot; Chromium chunking applied.
getClientVersiontrueReturns the Zotero desktop client version string (from ping).
reportActiveURLfalseReports the currently active tab URL to Zotero; fire-and-forget.
getPreftrueReturns a named connector preference value from the cached prefs object.
saveSingleFile hooks (Chromium only):
  • inject.preSend — calls Zotero.Messaging.sendAsChunks(args[1].snapshotContent) and replaces the content with the chunk ID, avoiding Chrome’s message size limit
  • background.postReceive — calls Zotero.Messaging.getChunkedPayload(args[1].snapshotContent) to reassemble the chunked payload before passing to the background function
The chunking path in saveSingleFile is active only when Zotero.isChromium is true. On Firefox and Safari the snapshot content is passed directly.
Browser-side UI and tab management calls, invoked from background to injected scripts.
MethodValueNotes
onSelecttrueNotifies inject of a library/collection selection.
onPageLoadfalseFires on page load; fire-and-forget.
onTranslatorsObjectDelivers available translators for the current page.
onZoteroButtonElementClicktrueHandles toolbar button click forwarding.
injectScriptstrueRequests dynamic script injection into the tab.
injectSingleFiletrueRequests SingleFile script injection.
isIncognitotrueReturns whether the current tab is in a private/incognito window.
isTabFocusedtrueReturns whether the tab is currently focused.
newerVersionRequiredPrompttrueDisplays the “update Zotero” prompt; returns user choice.
openTabfalseOpens a new tab; fire-and-forget.
openConfigEditorfalseOpens the advanced config editor; fire-and-forget.
openPreferencesfalseOpens the preferences page; fire-and-forget.
bringToFronttrueBrings a window to the foreground.
onTranslators hooks:
  • inject.preSend — serializes the translators array with t.serialize(TRANSLATOR_PASSING_PROPERTIES) before sending to the background, keeping only the fields needed across the boundary
Safari-only methods (added at runtime when Zotero.isSafari is true):
MethodValueNotes
onPDFFramefalseSignals detection of a PDF in a frame; fire-and-forget.
onPerformCommandfalseHandles a Safari toolbar command; fire-and-forget.
onTabFocusfalseNotifies on tab focus events; fire-and-forget.
onTabDatatrueRequests tab metadata from the native layer.
getExtensionVersiontrueReturns the Safari extension version string.
Exposes debug state queries from the injected/UI context to the background, where Zotero.Debug lives.
MethodValueNotes
storingtrueReturns true if debug output is currently being stored.
gettrueReturns the full debug log as a string.
counttrueReturns the number of lines currently in the debug log.
Handles saving items and attachments, both to Zotero desktop and to the Zotero web API server.
MethodValueNotes
saveAttachmentToZoterotrueSaves an attachment to the connected Zotero desktop.
saveStandaloneAttachmentToZoterotrueSaves a standalone attachment (e.g., PDF) directly to Zotero desktop.
saveAttachmentToServerObjectSaves an HTML attachment to the Zotero web server; Chromium chunking applied.
saveAttachmentToServer hooks (Chromium only):
  • inject.preSend — for text/html attachments whose data is a string, calls Zotero.Messaging.sendAsChunks(attachment.data) and replaces data with the chunk ID
  • background.postReceive — reassembles the chunked HTML with Zotero.Messaging.getChunkedPayload(attachment.data), then appends the current tab object as the last argument before calling the background function
Error collection and system information retrieval from the background.
MethodValueNotes
logfalseLogs an error object; fire-and-forget.
getErrorstrueReturns the array of logged errors.
getSystemInfotrueReturns a JSON string of system information (browser, OS, extension version, etc.).
Internal messaging infrastructure methods, used by the messaging layer itself.
MethodValueNotes
sendMessageObjectSends a message to a specific tab/frame; background injects tab and frameId.
receiveChunktrueStores an incoming chunk of a large chunked payload for later reassembly.
sendMessage hooks:
  • background.postReceive — ensures args[2] is the current tab object (appending it if not present), and ensures args[3] is the frameId (defaulting to 0 for the top frame)
Zotero Web API OAuth authorization and item/attachment operations.
MethodValueNotes
authorizetrueInitiates the OAuth authorization flow; resolves with user info on success.
onAuthorizationCompletefalseCalled when the OAuth callback page is reached; fire-and-forget.
clearCredentialsfalseRemoves stored OAuth credentials; fire-and-forget.
getUserInfotrueReturns stored OAuth user info (auth-token_secret, auth-userID, auth-username) or null.
runtrueRuns an API operation.
uploadAttachmentObjectUploads a binary attachment; ArrayBuffer is packed/unpacked across the boundary.
uploadAttachment hooks:
  • inject.preSend — calls packArrayBuffer(args[0].data) to convert the ArrayBuffer to a serializable form (base64 on Safari, byte array on MV3, blob URL on MV2 Chromium)
  • background.postReceive — calls unpackArrayBuffer(args[0].data) to restore the original ArrayBuffer
Safari-only overrides (set when Zotero.isSafari is true):
MethodValueNotes
createItemtrueCreates a Zotero web API item directly from the background (Safari only).
uploadAttachmentfalseOn Safari, attachment upload is fire-and-forget (handled natively).
Google Docs citation integration, bridging the connector injected into docs.google.com and the background Apps Script runner.
MethodValueNotes
onAuthCompletefalseSignals completion of Google OAuth; fire-and-forget.
runObjectRuns a Google Apps Script function.
getDocumenttrueFetches the current Google Doc structure.
batchUpdateDocumenttrueApplies a batch of updates to the Google Doc.
run configuration:
  • background.minArgs: 3 — args array is padded to at least 3 elements before the background function is called
Preference read/write operations from injected scripts, backed by browser.storage.local in the background.
MethodValueNotes
setfalseSets a preference value; fire-and-forget.
getAlltrueReturns all stored preferences as an object.
getDefaulttrueReturns the default value for a preference key.
getAsynctrueReturns a preference value (or object of values for an array of keys).
removeAllCachedTranslatorstrueClears all cached translator code from storage; returns when complete.
clearfalseRemoves a preference key (or array of keys); fire-and-forget.
Proxy configuration management from the preferences UI to the background.
MethodValueNotes
loadPrefsfalseReloads proxy preferences in the background; fire-and-forget.
validatetrueValidates a proxy configuration object; returns an error tuple or null.
savefalsePersists a proxy configuration; fire-and-forget.
removefalseRemoves a proxy configuration; fire-and-forget.
toggleRedirectLoopPreventionfalseEnables or disables redirect loop prevention; fire-and-forget.
Controls browser web request interception for user-agent spoofing.
MethodValueNotes
replaceUserAgenttrueSets a custom User-Agent string on intercepted requests; returns the previous value.
Controls interception of importable file types (BibTeX, RIS, etc.) for direct import into Zotero.
MethodValueNotes
handleImportableStyletrueHandles detection of a CSS/style file for import.
handleImportableContenttrueHandles detection of a BibTeX/RIS/Refer file for import.
enablefalseEnables content-type interception globally; fire-and-forget.
disablefalseDisables content-type interception globally; fire-and-forget.
Cross-origin HTTP — proxies XHR requests through the background to work around content-script network restrictions. The background performs the actual request; the inject side receives a reconstructed XHR-like object.
MethodValueNotes
requestObjectPerforms an XHR in the background and returns a reconstructed response object.
request hooks:background.preSend — strips the non-serializable responseXML property and builds a plain result object:
{
  response,        // packed if ArrayBuffer
  responseType,
  status,
  statusText,
  responseHeaders, // from xhr.getAllResponseHeaders()
  responseURL
}
If response is an ArrayBuffer, it is packed via packArrayBuffer before sending.inject.postReceive — reconstructs the XHR-like interface on the received object:
  • Attaches getAllResponseHeaders() and getResponseHeader(name) methods backed by the responseHeaders string
  • Detects the packed format (Safari base64, MV3 byte array, MV2 blob URL) and calls unpackArrayBuffer if needed; otherwise assigns responseText = response
Internationalization string retrieval, added only when Zotero.isSafari is true.
MethodValueNotes
getStringstrueReturns localized string map for the current locale.

Adding a New Message

1

Register the method in MESSAGES

Open src/common/messages.js and add your method to the appropriate namespace (or create a new namespace):
var MESSAGES = {
  // ... existing namespaces ...
  MyNamespace: {
    myMethod: true,           // expects a response
    myFireAndForget: false,   // no response
    myMethodWithHooks: {      // advanced
      inject: {
        preSend: async function(args) {
          // transform args before sending from injected page
          return args;
        }
      },
      background: {
        postReceive: async function(args, tab, frameId) {
          // transform args after receipt in background, append tab
          args.push(tab);
          return args;
        }
      }
    }
  }
};
2

Implement the handler in the background

In your background module, implement Zotero.MyNamespace.myMethod. The messaging layer automatically routes MyNamespace.myMethod calls to Zotero.MyNamespace.myMethod(…args, tab, frameId).
Zotero.MyNamespace = new function() {
  this.myMethod = async function(arg1, arg2, tab, frameId) {
    // your implementation
    return result;
  };
};
3

Call it from an injected script

No additional wiring is needed. The messaging_inject.js layer monkey-patches Zotero.MyNamespace.myMethod at startup:
// In any injected script context:
const result = await Zotero.MyNamespace.myMethod(arg1, arg2);
If your method needs to pass an ArrayBuffer across the boundary (e.g., binary file content), use the packArrayBuffer / unpackArrayBuffer helpers defined in messages.js as shown in the API.uploadAttachment and COHTTP.request entries above.

Build docs developers (and LLMs) love