188BET靠谱吗Zotero JavaScript API
188BET靠谱吗Whereas Zotero'sWeb API188BET靠谱吗allows read and write access to online Zotero libraries, it is also possible to access the local Zotero client through the local JavaScript API.(It is also possible todirectly access the local SQLite database, but that approach is much more fragile.)
Note that the (mostly user-contributed) documentation of the JavaScript API is not comprehensive.If you use the JavaScript API in ways beyond what's described here, please consider expanding this wiki page.
188BET靠谱吗Running Ad Hoc JavaScript in Zotero
188BET靠谱吗Zotero includes an option to run arbitrary privileged JavaScript:
-
In the Tools → Developer menu, select Run JavaScript.Opening the Error Console, which appears in the same menu, will also be helpful.
-
In the window that opens, enter some JavaScript in the Code textbox and click Run or press Cmd-R/Ctrl-R.
When runningasynchronouscode containingawait
, the entered code is wrapped in anasync function, allowing you to wait for the resolution of promises returned by functions.188BET靠谱吗Most Zotero functions that access the database, disk, or network are asynchronous.In this mode, the value of areturn
statement will be displayed in the right-hand pane upon successful completion.E.g.returning the currently selected item(s)
varitems=188BET靠谱吗Zotero.188BET靠谱吗getActiveZoteroPane().getSelectedItems();returnitems;
Insynchronousmode, the value of the final line will appear in the right-hand pane.The same result as above could be achieved in synchronous mode with
varitems=188BET靠谱吗Zotero.188BET靠谱吗getActiveZoteroPane().getSelectedItems();items;
188BET靠谱吗Zotero Code Architecture
Window Scope vs.Non-Window Scope
188BET靠谱吗Zotero code exists in either window scope and non-window scope.
188BET靠谱吗Window scope applies to code that runs within either the main Zotero window or a secondary window (e.g., the Advanced Search window).It has access to the window's DOM and can interact with the UI.188BET靠谱吗The main window-scope object in Zotero is188BET靠谱吗ZoteroPane
188BET靠谱吗, from zoteroPane.js, which controls most interactions triggered in the main Zotero window.
Non-window scope applies to lower-level code that doesn't have access to the DOM.This includes the core188BET靠谱吗
object, which contains all other non-window code, including the data layer used for retrieving and modifying library data.188BET靠谱吗In Zotero, non-window code is contained within thexpcom
subdirectory.
188BET靠谱吗Windows in Zotero can import the core188BET靠谱吗
object via the include.js script.188BET靠谱吗Zotero methods can then be called from anywhere within the window's scope simply by calling, for example,188BET靠谱吗var item = Zotero.Items.get(1);
.
188BET靠谱吗To access Zotero functionality from your own extension, you will need access to the core188BET靠谱吗
object.188BET靠谱吗If your extension operates within the main Zotero window, you already have access to the188BET靠谱吗
object and don't need to take further steps.188BET靠谱吗Otherwise, you can import the Zotero object into other windows by including the script chrome://zotero/content/include.js within an HTML or XUL file:
<scriptsrc=188BET靠谱吗"chrome://zotero/content/include.js"><script>
Once you have188BET靠谱吗
, you can get the current188BET靠谱吗ZoteroPane
object:
varzp=188BET靠谱吗Zotero.188BET靠谱吗getActiveZoteroPane();varitems=zp.getSelectedItems();
188BET靠谱吗(The Zotero pane will always be available unless the main window is closed, as is possible on macOS.)
Notification System
188BET靠谱吗Zotero has a built-in notification system that allows other privileged code to be notified when a change is made via the data layer — for example, when an item is added to the library.188BET靠谱吗Within Zotero itself, this is used mostly to update the UI when items change, but extensions can use the system to perform additional operations when specific events occur — say, to sync item metadata with a web-based API.
Available events:
-
add (c, s, i, t, ci, it)
-
modify (c, s, i, t)
-
delete (c, s, i, t)
-
remove (ci, it)
-
move (c, for changing collection parent)
c = collection, s = search (saved search), i = item, t = tag, ci = collection-item, it = item-tag
188BET靠谱吗See the ZoteroSample Pluginfor a demonstration.
API Methods
188BET靠谱吗The Zotero JavaScript API is under-documented, and at present requires a lot of looking around in the source code.188BET靠谱吗The most useful parts of the source code are in chrome/content/zotero/xpcom and xpcom/data, and the chrome/content/zotero (particularly zoteroPane.js and fileInterface.js).
Adding items and modifying data
A typical operation might include a call to188BET靠谱吗Zotero.Items.get()
to retrieve a188BET靠谱吗Zotero.Item
instance, calls to188BET靠谱吗Zotero.Item
methods on the retrieved object to modify data, and finally asave()
(within a transaction) orsaveTx()
(outside a transaction) to save the modified data to the database.
varitem=new188BET靠谱吗Zotero.Item('book');item.setField('title','Much Ado About Nothing');item.setCreators([{firstName:"William",lastName:"Shakespeare",creatorType:"author"}]);varitemID=await item.saveTx();returnitemID;
// Fetch saved items with Items.get(itemID)varitem=188BET靠谱吗Zotero.Items.get(itemID);alert(item.getField('title'));// "Much Ado About Nothing"alert(item.getCreator(0));// {'firstName'=>'William', 'lastName'=>'Shakespeare',// 'creatorTypeID'=>1, 'fieldMode'=>0}// Alternative formatalert(item.getCreatorJSON(0));// {'firstName'=>'William', 'lastName'=>'Shakespeare',// 'creatorType'=>'author'}item.setField('place','England');item.setField('date',1599);await item.saveTx();// update database with new data
188BET靠谱吗Get the Zotero Pane to interact with the Zotero UI
var188BET靠谱吗ZoteroPane=188BET靠谱吗Zotero.188BET靠谱吗getActiveZoteroPane();
188BET靠谱吗Then grab the currently selected items from the Zotero pane:
// Get first selected itemvarselectedItems=188BET靠谱吗ZoteroPane.getSelectedItems();varitem=selectedItems[0];// Proceed if an item is selected and it isn't a noteif(item&&!item.isNote()){if(item.isAttachment()){// find out about attachment}if(item.isRegularItem()){// We could grab attachments:// let attachmentIDs = item.getAttachments();188BET靠谱吗// let attachment = Zotero.Items.get(attachmentIDs[0]);}alert(item.id);}
Collection Operations
Get the items in the selected collection
varcollection=188BET靠谱吗ZoteroPane.getSelectedCollection();varitems=collection.getChildItems();// or you can obtain an array of itemIDs instead:varitemIDs=collection.getChildItems(true);
Create a subcollection of the selected collection
varcurrentCollection=188BET靠谱吗ZoteroPane.getSelectedCollection();varcollection=new188BET靠谱吗Zotero.Collection();collection.name=name;collection.parentID=currentCollection.id;varcollectionID=await collection.saveTx();returncollectionID;
188BET靠谱吗Zotero Search Basics
188BET靠谱吗If you are focused on data access, the first thing you will want to do will be to retrieve items from your Zotero library.Creating an in-memory search is a good start.
vars=new188BET靠谱吗Zotero.Search();s.libraryID=188BET靠谱吗Zotero.Libraries.userLibraryID;
Search for items containing a specific tag
Starting with the above code, we then use the following code to retrieve items in My Library with a particular tag:
s.addCondition('tag','is','tag name here');varitemIDs=await s.search();
Advanced searches
vars=new188BET靠谱吗Zotero.Search();s.libraryID=188BET靠谱吗Zotero.Libraries.userLibraryID;s.addCondition('joinMode','any');// joinMode defaults to 'all' as per the// advanced search UI
To add the other conditions available in the advanced search UI, use the following:
s.addCondition('recursive','true');// equivalent of "Search subfolders" checkeds.addCondition('noChildren','true');// "Only show top level childrens.addCondition('includeParentsAndChildren','true');"Include parent and child ..."
188BET靠谱吗There are also some "hidden" search conditions around line 1735 of chrome/content/zotero/xpcom/search.js in the Zotero source code (although some should only be used internally).[TODO remove mention of source code and enumerate all conditions]
One example is:
s.addCondition('deleted','true');// Include deleted items
Search by collection
To search for a collection or a saved search you need to know the ID or key:
s.addCondition('collectionID','is',collectionID);// e.g., 52s.addCondition('savedSearchID','is',savedSearchID);
s.addCondition('collection','is',collectionKey);// e.g., 'C72FDAP2's.addCondition('savedSearch','is',savedSearchKey);
Search by creator
varname='smith';s.addCondition('creator','contains',name);
Search by tag
To search by tag, you use the tag text:
vartagName='something';s.addCondition('tag','is',tagName);
Search by other fields
The complete list of other fields available to search on is on thesearch fieldspage.
Executing the search
Once the search conditions have been set up, then it's time to execute the results:
varitemIDs=await s.search();
This returns the item ids in the search as an array.188BET靠谱吗The next thing to do is to get the Zotero items for the array of IDs:
varitems=188BET靠谱吗await Zotero.Items.getAsync(itemIDs);
Managing citations and bibliographies
TODO: this is pretty sparse.the rtfscan code is a good place to look for some guidance.
Getting a bibliography for an array of items:
188BET靠谱吗Here we use Zotero's Quick Copy functions to get a bibliography in the style specified in Zotero's preferences.We will in the following example create this bibliography from all currently selected items.
varitems=188BET靠谱吗Zotero.188BET靠谱吗getActiveZoteroPane().getSelectedItems();varqc=188BET靠谱吗Zotero.QuickCopy;varformat=188BET靠谱吗Zotero.Prefs.get("export.quickCopy.setting");if(format.split("=")[0]!=="bibliography"){alert("No bibliography style is choosen in the settings for QuickCopy.");}varbiblio=qc.getContentFromItems(items,format);varbiblio_html_format=biblio.html;varbiblio_txt=biblio.text;
If you instead want to have the citation string then simply replace the 7th line withvar biblio = qc.getContentFromItems(items, format, null, true);
.
Get a list of available styles
188BET靠谱吗await Zotero.Schema.schemeUpdatePromise;varstyles=188BET靠谱吗Zotero.Styles.getVisible();varstyleInfo=[];for(let style of styles){styleInfo.push({id:style.styleID,name:style.title});}returnstyleInfo;
TODO: change the style.get stuff in other formats, especially RTF
Get information about an item.
TODO: need to list all the possible fields here, and what kind of entry they belong to.
188BET靠谱吗To get an item's abstract, we get the 'abstractNote' field from the Zotero item:
varabstract=item.getField('abstractNote');
Get child notes for an item
To get the child notes for an item, we use the following code:
varnoteIDs=item.getNotes();
This returns an array of ids of note items.To get each note in turn we just iterate through the array:
for(let id of noteIDs){let note=188BET靠谱吗Zotero.Items.get(id);let noteHTML=note.getNote();}
Get an item's related items
varrelatedItems=item.relatedItems;
Set two items as related to each other
Given two itemsitemA
anditemB
.We can set them as related items to each other by using theaddRelatedItem
function:
itemA.addRelatedItem(itemB);await itemA.saveTx();itemB.addRelatedItem(itemA);await itemB.saveTx();
Get an item's attachments
Here's some example code to get the full text of HTML and PDF items in storage and put the data in an array:
varitem=188BET靠谱吗ZoteroPane.getSelectedItems()[0];varfulltext=[];if(item.isRegularItem()){// not an attachment alreadylet attachmentIDs=item.getAttachments();for(let id of attachmentIDs){let attachment=188BET靠谱吗Zotero.Items.get(id);if(attachment.attachmentContentType=='application/pdf'||attachment.attachmentContentType=='text/html'){fulltext.push(await attachment.attachmentText);}}}returnfulltext;
File I/O
Getting the contents of a file
varpath='/Users/user/Desktop/data.json';vardata=188BET靠谱吗await Zotero.File.getContentsAsync(path);
Saving data to a file
varpath='/Users/user/Desktop/file.txt';vardata="This is some text.";188BET靠谱吗await Zotero.File.putContentsAsync(path,data);
To Do
-
188BET靠谱吗Select a Zotero saved search
-
Combining search terms
-
Complete list of search operators
-
Complete list of search fields - with description of what the more obscure fields mean - e.g.abstractNote for abstract, and how do we search the fulltext archive?
-
fulltext for an item
-
Get stored attachments for an item
Batch Editing
188BET靠谱吗The JavaScript API provides a powerful way to script changes to your Zotero library.The common case of search-and-replace is accomplished easily using a basic script in theJavaScript runner.
Before proceeding, back up your188BET靠谱吗Zotero data directory188BET靠谱吗and temporarily disable auto-sync in the Sync pane of the Zotero preferences.
All examples operate on the currently selected library.
Example: Item Field Changes
Edit the first three lines as necessary:
varfieldName="publicationTitle";varoldValue="Foo";varnewValue="Foo2";varfieldID=188BET靠谱吗Zotero.ItemFields.getID(fieldName);vars=new188BET靠谱吗Zotero.Search();s.libraryID=188BET靠谱吗ZoteroPane.getSelectedLibraryID();s.addCondition(fieldName,'is',oldValue);varids=await s.search();if(!ids.length){return"No items found";}188BET靠谱吗await Zotero.DB.executeTransaction(asyncfunction(){for(let id of ids){let item=188BET靠谱吗await Zotero.Items.getAsync(id);let mappedFieldID=188BET靠谱吗Zotero.ItemFields.getFieldIDFromTypeAndBase(item.itemTypeID,fieldName);item.setField(mappedFieldID?mappedFieldID:fieldID,newValue);await item.save();}});returnids.length+" item(s) updated";
The list of field names to use can be retrieved via the web API:
Example: Creator Name Changes
Edit the first four lines as necessary:
varoldName="Robert L.Smith";varnewFirstName="Robert";varnewLastName="Smith";varnewFieldMode=0;// 0: two-field, 1: one-field (with empty first name)vars=new188BET靠谱吗Zotero.Search();s.libraryID=188BET靠谱吗ZoteroPane.getSelectedLibraryID();s.addCondition('creator','is',oldName);varids=await s.search();if(!ids.length){return"No items found";}188BET靠谱吗await Zotero.DB.executeTransaction(asyncfunction(){for(let id of ids){let item=188BET靠谱吗await Zotero.Items.getAsync(id);let creators=item.getCreators();let newCreators=[];for(let creator of creators){if(`${creator.firstName}${creator.lastName}`.trim()==oldName){creator.firstName=newFirstName;creator.lastName=newLastName;creator.fieldMode=newFieldMode;}newCreators.push(creator);}item.setCreators(newCreators);await item.save();}});returnids.length+" item(s) updated";
Example: Convert Manual Tag to Automatic
Note that this will change all instances of the tag in the library.
Replace "Foo" in the first line with the tag to change:
vartag="Foo";vars=new188BET靠谱吗Zotero.Search();s.libraryID=188BET靠谱吗ZoteroPane.getSelectedLibraryID();s.addCondition('tag','is',tag);varids=await s.search();if(!ids.length){return"No items found";}188BET靠谱吗await Zotero.DB.executeTransaction(asyncfunction(){for(let id of ids){let item=188BET靠谱吗Zotero.Items.get(id);item.addTag(tag,1);await item.save({skipDateModifiedUpdate:true});}});returnids.length+" tag(s) updated";
Example: Delete Tags By Part of Name
188BET靠谱吗This example has not been updated for Zotero 5 and should not currently be used.
vartags=["foo","bar","baz"];varids=[];tags.forEach(function(tag){ids=ids.concat(Object.keys(188BET靠谱吗Zotero.Tags.search(tag)));});188BET靠谱吗Zotero.Tags.erase(ids);