Note: The new Content Security Policy will prevent direct injection. Here is how to get around it
Note: This is not an official Gmail API, and isn't affiliated with Google.
Note: Gmail.js requires jQuery to work
- Lots of api methods to work with gmail. Useful for chrome extensions
- Most of them dont take arguments, they work on what is currently visible on the screen
- I still need to add implementation for chrome extension, works by injecting js for now
- Main methods allow you to observe certain events with
gmail.observe.on('lots_of_actions_here', callback())
or similargmail.observe.before(...)
andgmail.observe.after(...)
- Click on a method link to view more detailed docs
- Create an issue/pull request for feedback, requests and fixes
- Signal - Edit your inbox!
- Gmail Hacks by @arpitnext (Source)
The new Content Security Policy will prevent direct injection. Please see the following repository to get around the policies. More details can also be found in issue #75
- Gmail.js requires jQuery to work
// {inject jquery.js} by copy pasting this in your console
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
document.getElementsByTagName('body')[0].appendChild(jq);
// {inject gmail.js} by copy pasting gmail.js contents or via url like jquery above
// var Gmail = {.....} // paste gmail.js code here
// start using!
// you can also pass in a reference to jQuery upon init - Gmail(localJQuery)
var gmail = Gmail();
gmail.get.user_email();
- gmail.get .user_email()
- gmail.get .visible_emails()
- gmail.get .selected_emails_data()
- gmail.get .current_page()
- gmail.get .email_id()
- gmail.get .email_ids()
- gmail.get .email_subject()
- gmail.get .compose_ids()
- gmail.get .email_data(email_id=undefined)
- gmail.get .displayed_email_data()
- gmail.get .email_source(email_id=undefined)
- gmail.get .search_query()
- gmail.get .unread_emails()
- gmail.get .unread_inbox_emails()
- gmail.get .unread_draft_emails()
- gmail.get .unread_spam_emails()
- gmail.get .unread_forum_emails()
- gmail.get .unread_update_emails()
- gmail.get .unread_promotion_emails()
- gmail.get .unread_social_emails()
- gmail.get .last_active()
- gmail.get .storage_info()
- gmail.get .loggedin_accounts()
- gmail.get .beta()
- gmail.get .localization()
- gmail.check .is_thread()
- gmail.check .is_inside_email()
- gmail.check .is_preview_pane()
- gmail.check .is_multiple_inbox()
- gmail.check .is_horizontal_split()
- gmail.check .are_shortcuts_enabled()
- gmail.check .is_vertical_split()
- gmail.check .is_tabbed_inbox()
- gmail.check .is_right_side_chat()
- gmail.check .is_conversation_view()
- gmail.check .is_google_apps_user()
- gmail.check .is_priority_inbox()
- gmail.check .is_rapportive_installed()
- gmail.check .is_streak_installed()
- gmail.check .is_anydo_installed()
- gmail.check .is_boomerang_installed()
- gmail.check .is_xobni_installed()
- gmail.check .is_signal_installed()
- gmail.observe .http_requests()
- gmail.observe .actions()
- gmail.observe .register(action, class/args, parent) - registers a custom DOM observer
- gmail.observe .off(action,type)
- gmail.observe .on(action, callback)
poll
- When gmail automatically polls the server to check for new emails every few secondsnew_email
- When a new email appears in the inboxopen_email
- When an email is opened from the inbox viewrefresh
- When you click the refresh buttonunread
- When a conversation(s) is marked unreadread
- When a conversation(s) is marked readdelete
- When a conversation(s) is deleteddelete_message_in_thread
- When a conversation(s) is deleted inside a threadmark_as_spam
- When a conversation(s) is marked as spammark_as_not_spam
- When a conversation(s) is unchecked as spamlabel
- When a conversation(s) get applied a labelarchive
- When a conversation(s) is archievedmove_to_inbox
- When a conversation(s) is moved to the inboxdelete_forever
- When a conversation(s) is deleted foreverstar
- When a conversation(s) is starredunstar
- When a conversation(s) is unstarredmark_as_important
- When a conversation(s) is marked as importantmark_as_not_important
- When a conversation(s) is marked as not importantfilter_messages_like_these
- When a filter button is triggered for a conversationmute
- When a conversation(s) is mutedunmute
- When a conversation(s) is unmutedadd_to_tasks
- When an item is added to google tasksmove_label
- When a conversation(s) is moved to a label foldersave_draft
- When a draft is saveddiscard_draft
- When a draft is dicardedsend_message
- When a message is sentexpand_categories
- When a category is expanded from the left nav sidebarrestore_message_in_thread
- When a deleted message is restored inside a threaddelete_label
- When a label is deletedshow_newly_arrived_message
- When inside an email and a new email arrives in the threadupload_attachment
- When an attachment is being uploaded to an email being composed- DOM observers
compose
- When a new compose window is opened, or a message is replied to or forwardedrecipient_change
- When an email being written (either new compose, reply or forward) has its to, cc or bcc recipients updatedview_thread
- When a conversation thread is opened to readview_email
- Sub-observer toview_thread
. When an individual email is loaded within a conversation threadload_email_menu
- Sub-observer toview_thread
. When the dropdown menu next to the reply button is clicked
- gmail.observe .before(action, callback)
- gmail.observe .after(action, callback)
- gmail.observe .bind(type, action, callback) - implements the on, after, before callbacks
- gmail.observe .bound(action, type)
- gmail.observe .on_dom(action, callback) - implements the DOM observers - called by
gmail.observe.on
- gmail.observe .bound(action, type) - checks if a specific action and/or type has any bound observers
- gmail.observe .trigger(type, events, xhr) - fires any specified events for this type (on, after, before) with specified parameters
These methods return the DOM data itself
- gmail.dom .inboxes()
- gmail.dom .inbox_content()
- gmail.dom .email_subject()
- gmail.dom .email_body()
- gmail.dom .email_contents()
- gmail.dom .get_left_sidebar_links()
- gmail.dom .search_bar()
- gmail.dom .toolbar()
- gmail.dom .compose() - compose dom object - receives the DOM element for the compose window and provides methods to interact
- gmail.dom .composes() - retrives an array of
gmail.dom.compose
objects representing any open compose windows - gmail.dom .email() - email dom object - receives an email DOM element or email id for an email currently being viewed. Abstracts interaction with that email.
- gmail.dom .thread() - thread dom object - receives a conversation thread DOM element currently being viewed. Abstracts interaction with that thread.
These are some helper functions that the rest of the methods use. See source for input params
- gmail.tools infobox(message, time)
- Adds the yellow info box on top of gmail with the given message
- gmail.tools rerender(callback)
- Re-renders the UI using the available data.
- gmail.tools .xhr_watcher()
- gmail.tools .parse_url()
- gmail.tools .deparam()
- gmail.tools .parse_view_data()
- gmail.tools .parse_email_data()
- gmail.tools .extract_email_address(str)
- gmail.tools .extract_name(str)
- gmail.tools .make_request()
- gmail.tools .sleep(ms)
- gmail.tools .multitry(ms_delay, tries, func, bool_success_check)
- gmail.tools .i18n(label)
- gmail.tools add_toolbar_button(content_html, onclick_action, custom_style_class)
- gmail.tools add_compose_button(compose_ref,content_html, onclick_action, custom_style_class)
These are some of the variables that are tracked and kept in memory while the rest of the methods are in use.
- gmail.version
- gmail.tracker .events
- gmail.tracker .xhr_init
- gmail.tracker .xhr_open
- gmail.tracker .xhr_send
- gmail.tracker .watchdog
- gmail.tracker .view_data
- gmail.tracker .email_data
- gmail.tracker .ik
- gmail.tracker .rid
Returns a list of emails from the server that are currently visible in the inbox view. The data does not come from the DOM
[{"id": "1425a3693a4c45d0",
"title": "<b>What if video games were real? On YouTube</b>",
"excerpt": "View email in a web browser Header Super Mario Brothers Parkour by Warialasky Super Mario Brothers",
"time": "Fri, Nov 15, 2013 at 12:23 AM",
"sender": "noreply@youtube.com",
"attachment": "",
"labels": ["^all", "^i", "^smartlabel_social", "^unsub"]}]
Returns a list of object representation from emails that are currently selected in the inbox view. The data does not come from the DOM
[{
"thread_id":"141d44da39d6caf8",
"first_email": "141d44da39d6caf9",
"last_email": "141d44da39d6caf9",
"total_emails": 1,
"total_threads": ["141d44da39d6caf8"],
"people_involved": [
["Kartik Talwar", "hi@kartikt.com"],
["California", "california@gmail.com"]
],
"subject": "test",
"threads": {
"141d44da39d6caf8": {
"reply_to_id": "",
"is_deleted" : false,
"from": "California",
"to" : ["hi@kartikt.com"],
"cc" : [],
"bcc" : [],
"from_email": "california@gmail.com",
"timestamp": 1382246359000,
"datetime": "Sun, Nov 20, 2013 at 1:19 AM",
"content_plain": "another test",
"subject": "test",
"content_html": "<div dir=\"ltr\">another test</div>\n"
}
}
},{
"thread_id":"141d44da39d6caf8",
"first_email": "141d44da39d6caf8",
"last_email": "141d44da39d6caf8",
"total_emails": 1,
"total_threads": ["141d44da39d6caf8"],
"people_involved": [
["Kartik Talwar", "hi@kartikt.com"],
["California", "california@gmail.com"]
],
"subject": "test",
"threads": {
"141d44da39d6caf8": {
"reply_to_id": "",
"is_deleted" : false,
"from": "California",
"to" : ["hi@kartikt.com"],
"cc" : [],
"bcc" : [],
"from_email": "california@gmail.com",
"timestamp": 1382246359000,
"datetime": "Sun, Nov 20, 2013 at 1:19 AM",
"content_plain": "another test",
"subject": "test",
"content_html": "<div dir=\"ltr\">another test</div>\n"
}
}
}]
Returns an object representation of the opened email contents and metadata. It takes the optional email_id parameter where the data for the specified id is returned instead of the email currently visible in the dom.
thread_id
is added for updated gmail thread behaviour which adds support for emails created in inbox. first_email remains as the first message in the thread.
{
"thread_id":"141d44da39d6caf8",
"first_email": "141d44da39d6caf8",
"last_email": "141d44da39d6caf8",
"total_emails": 1,
"total_threads": ["141d44da39d6caf8"],
"people_involved": [
["Kartik Talwar", "hi@kartikt.com"],
["California", "california@gmail.com"]
],
"subject": "test",
"threads": {
"141d44da39d6caf8": {
"reply_to_id": "",
"is_deleted" : false,
"from": "California",
"to" : ["hi@kartikt.com"],
"cc" : [],
"bcc" : [],
"from_email": "california@gmail.com",
"timestamp": 1382246359000,
"datetime": "Sun, Nov 20, 2013 at 1:19 AM",
"content_plain": "another test",
"subject": "test",
"content_html": "<div dir=\"ltr\">another test</div>\n"
}
}
}
Returns an object representation of the emails that are being displayed.
{
"thread_id":"141d44da39d6caf8",
"first_email": "145881e7a8befff6",
"last_email": "145881e7a8befff6",
"total_emails": 1,
"total_threads": ["145881e7a8befff6"],
"people_involved": [
["Kartik Talwar", "hi@kartikt.com"],
["California", "california@gmail.com"]
],
"subject": "test",
"threads": {
"145881e7a8befff6": {
"reply_to_id": "",
"is_deleted" : false,
"from": "California",
"to" : ["hi@kartikt.com"],
"cc" : [],
"bcc" : [],
"from_email": "california@gmail.com",
"timestamp": 1382246359000,
"datetime": "Sun, Nov 20, 2013 at 1:19 AM",
"content_plain": "another test",
"subject": "test",
"content_html": "<div dir=\"ltr\">another test</div>\n"
}
}
}
Retrieves raw MIME message source from the gmail server for the specified email id. It takes the optional email_id parameter where the data for the specified id is returned instead of the email currently visible in the dom
Returns the current user's email address
"california@gmail.com"
Returns current user's file storage stats
{
"used": "0 GB",
"total": "15 GB",
"percent": 0
}
Returns what page of gmail the user is currently on. These are the possible responses
['sent', 'inbox', 'starred', 'drafts', 'imp', 'chats', 'all', 'spam', 'trash', 'settings'] // pages
null // inside email conversation
"/search/[.+]" // inside search view
"/label/[.+]" // inside label view
"/category/[.+]" // inside category view
"/settings/[.+]" // settings sub-page (excluding settings root page)
Returns the opened email's subject from the DOM
"test"
Gets current email's ID
"141de25dc0b48e4f"
Returns a list of email IDs for each thread in the conversation
["141de25dc0b48e4f"]
Returns the latest/last email id of emails that have been saved as drafts (currently open)
["14469c73bba6ff53", "14469c7b8581ccfa"]
Returns the search bar data
"from:hi@kartikt.com is:unread"
Returns a count of total unread emails for the current account.
{
"inbox": 2,
"drafts": 0,
"spam": 0,
"forum": 0,
"notifications": 0,
"promotions": 0,
"social": 0
}
You can also request the data individually
- gmail.get.unread_inbox_emails()
- gmail.get.unread_draft_emails()
- gmail.get.unread_spam_emails()
- gmail.get.unread_forum_emails()
- gmail.get.unread_update_emails()
- gmail.get.unread_promotion_emails()
- gmail.get.unread_social_emails()
Gets user's account activity data
{
"time": "9:41 pm",
"ip": "54.234.192.48",
"mac_address": "2620:101:f000:702:a966:ab42:4a46:195e",
"time_relative": "31 minutes ago"
}
Returns a list of signed-in accounts (multiple user accounts setup in gmail)
[{"name":"California","email":"california@gmail.com"}]
Although hand picked, this method returns the checks on beta features and deployments
{"new_nav_bar":true}
Returns the Gmail localization, e.g. 'US'.
Returns True
if the conversation is threaded False
otherwise
Returns True
if gmail is in split pane mode (vertical or horizontal) False
otherwise
Returns True
if user has multiple inbox lab enabled, False
otherwise
Returns True
if the pane split mode is horiontal False
otherwise
Returns True
if user has enabled mail action shortcuts, False
otherwise
Returns True
if the pane mode is vertical False
otherwise
Returns True
if tabbed inbox view is enabled False
otherwise
Returns True
if chat is on the right sidebar False
otherwise
Returns True
if emails are displayed as threads, False
otherwise (i.e. displayed individually)
Returns True
if the current user is google apps user (email not ending in gmail.com) False
otherwise
Returns True
if you are currently inside an email conversation False
otherwise
Returns True
if priority inbox is enabled False
otherwise
Returns True
if rapportive chrome extension is installed False
otherwise
Returns True
if streak chrome extension is installed False
otherwise
Returns True
if any.do chrome extension is installed False
otherwise
Returns True
if boomerang chrome extension is installed False
otherwise
Returns True
if xobni chrome extension is installed False
otherwise
Returns True
if Signal chrome extension is installed False
otherwise
Returns True
if the account supports the new hangout UI for chat False
otherwise (native chat window)
-Clicks on the compose button making the inbox compose view to popup
After an observer has been bound through gmail.observe.bind()
(via a call to events gmail.observe.before()
, gmail.observe.on()
, or gmail.observe.after()
), this method keeps track of the last 50 http events.
The items contain the sent requested parameterized data
[{
"method": "POST",
"url": {
"ui": "2",
"ik": "13fa7f7088",
"rid": "ed0e..",
"view": "tl",
"start": "0",
"num": "30",
"lhop": "169846",
"ltup": "%5Ei",
"slmm": "1427abc6106ac10b",
"scid": "q2h353hw6dv9",
"avw": "1194",
"ntlv": "10",
"auto": "1",
"ver": "-z-h-bKmWwI.en.",
"am": "!6hSPXvkvPMjmReGu2-2BQXCk3IltF-jNSk0J8Cg_jNeaoSbpJgHQYdkXe6T_WPYyyATD3DSiOA",
"vas": "1",
"ari": "120",
"_reqid": "4582876",
"pcd": "1",
"mb": "0",
"rt": "j",
"search": "inbox"
},
"body": "",
"url_raw": "?ui=2&ik=13fa7f7088&rid=ed0e..&view=tl&start=0&num=30&lhop=169846<up=%5Ei&slmm=1427abc6106ac10b&scid=q2h353hw6dv9&avw=1194&ntlv=10&auto=1&ver=-z-h-bKmWwI.en.&am=!6hSPXvkvPMjmReGu2-2BQXCk3IltF-jNSk0J8Cg_jNeaoSbpJgHQYdkXe6T_WPYyyATD3DSiOA&vas=1&ari=120&_reqid=4582876&pcd=1&mb=0&rt=j&search=inbox"
}]
Similar to gmail.obsere.http_requests()
this keeps track of the last 10 gmail actions (vs all http requests).
Actions here correspond to things like clicking refres, archiving, deleting, starring etc.
This is the key feature of gmail.js. This method allows you to add triggers to all of these actions so you can build your custom extension/tool with this library.
You simply specify the action nane and your function that the method will return data to when the actions are triggered and it does the rest. You can have multiple triggers
Your callback will be fired directly after Gmail's XMLHttpRequest has been sent off the the Gmail servers.
Available Actions
- poll - When gmail automatically polls the server to check for new emails every few seconds
- new_email - When a new email appears in the inbox
- open_email - When a new email appears in the inbox
- refresh - When you click the refresh button
- unread - When a conversation(s) is marked unread
- read - When a conversation(s) is marked read
- delete - When a conversation(s) is deleted
- delete_message_in_thread - When a conversation(s) is deleted inside and is part of a thread
- mark_as_spam - When a conversation(s) is marked as spam
- mark_as_not_spam - When a conversation(s) is unchecked as spam
- label - When a conversation(s) get applied a label
- archive - When a conversation(s) is archieved
- move_to_inbox - When a conversation(s) is moved to the inbox
- delete_forever - When a conversation(s) is deleted forever
- star - When a conversation(s) is starred
- unstar - When a conversation(s) is unstarred
- mark_as_important - When a conversation(s) is marked as important
- mark_as_not_important - When a conversation(s) is marked as not important
- filter_messages_like_these - When a filter button is triggered for a conversation
- mute - When a conversation(s) is muted
- unmute - When a conversation(s) is unmuted
- add_to_tasks - When an item is added to google tasks
- move_label - When a conversation(s) is moved to a label folder
- save_draft - When a draft is saved
- discard_draft - When a draft is dicarded
- send_message - When a message is sent
- expand_categories - When a category is expanded from the left nav sidebar
- restore_message_in_thread - When a deleted message is restored inside a thread
- delete_label - When a label is deleted
- show_newly_arrived_message - When inside an email and a new email arrives in the thread
The on method also supports observering specific DOM events in the Gmail Interface (for example when a new compose window is opened). These are only available via the on
method (not the before
or after
methods).
Some actions/observers also have defined 'sub-observers' which become available if you have an action bound to the parent observer. Sub-observers are defined as such because they only make sense once the parent has been triggered. I.e. for an individual email to display as part of a conversation thread, the thread must first be opened/loaded in the interface.
Example usage:
gmail.observe.on('view_thread', function(obj) {
console.log('view_thread', obj);
});
// now we have access to the sub observers view_email and load_email_menu
gmail.observe.on('view_email', function(obj) {
console.log('view_email', obj);
});
Available DOM Actions/Observers & Sub-observers
- load - When the gmail interface has completed loading
- compose - When a new compose window opens, or a message is replied to or forwarded
- recipient_change - When the recipient (to, cc or bcc) is changed when composing a new email or replying/forwarding an email
- view_thread - When a new coversation thread is opened
- view_thread Sub-observers
- view_email - When an individual email is loaded within a thread (also fires when thread loads displaying the latest email)
- load_email_menu - When the dropdown menu next to the reply button is clicked
gmail.observe.on("unread", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("read", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("delete", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("mark_as_spam", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("mark_as_not_spam", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("label", function(id, url, body, label, xhr) {
console.log("id:", id, "url:", url, 'body', body, "label", label, 'xhr', xhr);
})
gmail.observe.on("archive", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("move_to_inbox", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("delete_forever", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("delete_message_in_thread", function(id, url, body) {
console.log("id:", id, "url:", url, 'body', body);
})
gmail.observe.on("restore_message_in_thread", function(id, url, body) {
console.log("id:", id, "url:", url, 'body', body);
})
gmail.observe.on("star", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("unstar", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("mark_as_important", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("mark_as_not_important", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("filter_messages_like_these", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("mute", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("unmute", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("add_to_tasks", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'task_data', data, 'xhr', xhr);
})
gmail.observe.on("move_label", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("save_draft", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'email_data', data, 'xhr', xhr);
})
gmail.observe.on("discard_draft", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("send_message", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'email_data', data, 'xhr', xhr);
})
gmail.observe.on("expand_categories", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'expanded_data', data, 'xhr', xhr);
})
gmail.observe.on("delete_label", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("show_newly_arrived_message", function(id, url, body) {
console.log("id:", id, "url:", url, 'body', body);
})
gmail.observe.on("poll", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'data', data, 'xhr', xhr);
})
gmail.observe.on("new_email", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
})
gmail.observe.on("refresh", function(url, body, data, xhr) {
console.log("url:", url, 'body', body, 'data', data, 'xhr', xhr);
})
gmail.observe.on("open_email", function(id, url, body, xhr) {
console.log("id:", id, "url:", url, 'body', body, 'xhr', xhr);
console.log(gmail.get.email_data(id));
})
gmail.observe.on("upload_attachment", function(file, xhr) {
console.log("file", file, 'xhr', xhr);
})
// DOM observers
gmail.observe.on("compose", function(compose, type) {
// type can be compose, reply or forward
console.log('api.dom.compose object:', compose, 'type is:', type ); // gmail.dom.compose object
});
gmail.observe.on('recipient_change', function(match, recipients) {
console.log('recipients changed', match, recipients);
});
gmail.observe.on('view_thread', function(obj) {
console.log('conversation thread opened', obj); // gmail.dom.thread object
});
gmail.observe.on('view_email', function(obj) {
console.log('individual email opened', obj); // gmail.dom.email object
});
gmail.observe.on('load_email_menu', function(match) {
console.log('Menu loaded',match);
// insert a new element into the menu
$('<div />').addClass('J-N-Jz')
.html('New element')
.appendTo(match);
});
Similar to gmail.observe.on
, this method allows you to bind callbacks to specific events.
All of the standard actions in gmail.observe.on
work here, with the exception of the DOM actions
The main difference between on
and before
is that these callbacks are fired before Gmail's XMLHttpRequest has been sent off the the Gmail servers.This means, where relevant, your callback function can change it prior to it departing by editing the xhrParams.body_params object in the passed xhr parameter.
gmail.observe.before('send_message', function(url, body, data, xhr){
var body_params = xhr.xhrParams.body_params;
// lets cc this email to someone extra if the subject is 'Fake example'
if(data.subject == 'Fake example') {
if(body_params.cc) {
if(typeof body_params.cc != 'object') body_params.cc = [ body_params.cc ];
} else {
body_params.cc = [];
}
body_params.cc.push('brent@zeald.com');
}
// now change the subject
body_params.subject = 'Subject overwritten!';
console.log("sending message, url:", url, 'body', body, 'email_data', data, 'xhr', xhr);
});
Similar to gmail.observe.on
, this method allows you to bind callbacks to specific events.
All of the standard actions in gmail.observe.on
work here, with the exception of the DOM actions
The main difference between on
and after
is that these callbacks are fired once Gmail's XMLHttpRequest has returned from the Gmail servers (on the XMLHttpRequest onreadystatechange
event).
In addition to the usual parameters received by a callback, callbacks you define for an after
event receive an additional response
parameter prior to the last xhr parameter. This response parameter is a parsed object representation of the response from the Gmail servers.
So for example, the send_message
action would receive:
gmail.observe.after("send_message", function(url, body, data, response, xhr) {
console.log("message sent", "url:", url, 'body', body, 'email_data', data, 'response', response, 'xhr', xhr);
})
Turn off an observe action. Providing it no argument will disable all observers.
Type is either before, after, on or dom. If not specified will disable all types of specified observer.
gmail.observe.on('poll', function(x,y,z){});
gmail.observe.before('refresh', function(x,y,z){});
gmail.observe.after('send_message', function(x,y,z){});
gmail.observe.off('poll','on'); // disables on poll
gmail.observe.off('poll'); // disables all poll events of any type
gmail.observe.off(null,'before'); // disables all before observers
gmail.observe.off(); // disables all
Allow an application to register a custom DOM observer specific to their application.
Adds it to the configured DOM observers that will then be supported by the dom insertion observer.
Note this method must be called prior to binding any handlers to specific actions/observers using on
, before
or after
.
Once you start binding handlers, you cannot register any further custom observers.
This method can be called two different ways:
Simple:
- action - the name of the new DOM observer
- class - the class of an inserted DOM element that identifies that this action should be triggered
- parent - optional - if specified, this observer will be registered as a sub_observer for the specified parent (meaning it will only be checked for if the parent observer has something bound to it, and has been triggered).
Complex:
- action - the name of the new DOM observer
- args - an object containin properties for each of the supported DOM observer configuration agruments:
- class - the class of an inserted DOM element that identifies that this action should be triggered
- selector - if you need to match more than just the className of a specific element to indicate a match, you can use this selector for further checking (uses element.is(selector) on matched element). E.g. if there are multiple elements with a class indicating an observer should fire, but you only want it to fire on a specific id, then you would use this
- sub_selector - if specified, we do a jquery element.find for the passed selector on the inserted element and ensure we can find a match
- handler - if specified this handler is called if a match is found. Otherwise default calls the callback & passes the jQuery matchElement
- parent - optional - as above with simple
// this will register an observer that fires each time the autosuggest listbox pops up / changes
// as you type an email address into a compose
gmail.observe.register('compose_email_select', {
class: 'Jd-axF',
selector: 'div.Jd-axF:first-child'
});
gmail.observe.on('compose_email_select', function(match) {
console.log('Email select popup',match);
});
An object used to abstract interation with a compose popup
An object for interacting with an email currently present in the DOM. Represents an individual email message within a thread, and provides a number of methods and properties to access & interact with the interface and email data.
Expects a jQuery DOM element for the email div (div.adn as returned by the view_email
observer), or an email_id
- .id - property storing the id of the email
- .body([body]) - allows get/set the html body in the DOM
- .to([to_array]) - allows retrieve or updating to/from DOM who the email is addressed to
- .from([email_address],[name]) - allows get/set who the email is from in the DOM
- .data() - retrieves object of email data from the Gmail servers
- .source() - retrieves the email raw source from the Gmail servers
- .dom() - retrieves the primary element, or other defined elements from the DOM
Get/Set the full email body as it sits in the DOM. Note: This gets & sets the body html after it has been parsed & marked up by GMAIL. To retrieve it as it exists in the email message source, use a call to .data()
If you want the actual DOM element use .dom('body');
Receives optional argument containing html to update the email body with.
var email = new gmail.dom.email(email_id); // optionally can pass relevant $('div.adn');
var body = email.body();
var id = email.id;
// add a heading at the start of the email and update in the interface
email.body('<h1>My New Heading!</h1>' + body);
Get/Set who the email is showing as To. Optionally receives an array of objects containing email and/or name properties. If received replaces the values in the DOM. Returns an array of objects containing email & name of who is showing in the DOM as the email is to.
var email = new gmail.dom.email(email_id);
var to = email.to();
console.log('Email is to', to); // [{email: 'user@user.com', name: 'Display Name'}, {email: 'user2@user.com', name: 'User Two'}]
// update values that appear in the interface. This supports the popup hovers in gmail interface etc
to = email.to([
{email: 'user@user.com', name: 'Display Name'},
{email: 'user2@user.com', name: 'User Two'}
]);
Get/Set the sender of the email that is displayed in the interface. Optionally receives email and name properties. If received updates the values in the DOM Returns an object containing email & name of the sender and dom element
var email = new gmail.dom.email(email_id);
var from = email.from();
console.log('Email is from', from); // {email: 'user@user.com', name: 'Display Name'}
// update who the email is from in the interface
from.name = 'New Name';
email.from(from);
Retrieve relevant email data from the Gmail servers for this email Makes use of the gmail.get.email_data() method Returns an object containing the email data. Caches email data for all emails in the thread
var email = new gmail.dom.email(email_id);
var data = email.data();
console.log('Email data is',data);
Retrieve email source for this email from the Gmail servers Makes use of the gmail.get.email_source() method Returns string of email raw source
var email = new gmail.dom.email(email_id);
var source = email.source();
console.log('Email source is',source);
Retrieve preconfigured dom elements for this email Abstracts relevant dom elements so code can be centralized - making it easier to update if Gmail updates its interface Retrieves the primary DOM element if you pass no lookup Supported lookups: - null (primary element) - body - from - to - to_wrapper - timestamp - star - reply_button - menu_button - details_button
var email = new gmail.dom.email(email_id);
var el = email.dom();
var to_dom = email.dom('to');
console.log('El is',el,'To elements are',to);
An object for interacting with a conversation thread currently present in the DOM. Provides methods to access & interact with the interface.
Expects a jQuery DOM element for the thread wrapper div (div.if as returned by the view_thread
observer)
- .dom() - retrieves the primary element, or other defined elements from the DOM
Retrieve preconfigured dom elements for this conversation thread Abstracts relevant dom elements so code can be centralized - making it easier to update if Gmail updates its interface Retrieves the primary DOM element if you pass no lookup Supported lookups: - null (primary element) - opened_email - subject - labels
var thread = new gmail.dom.thread($('div.if'));
var el = thread.dom();
var subject = thread.dom('subject');
console.log('El is',el,'Subject element is',subject);
Add a new button to Gmail Toolbar
gmail.tools.add_toolbar_button('content_html', function() {
// Code here
}, 'Custom Style Classes');
Add button to compose window. You can use gmail.dom.composes() to get compose reference.
var compose_ref = gmail.dom.composes()[0];
gmail.tools.add_compose_button(compose_ref, 'content_html', function() {
// Code here
}, 'Custom Style Classes');
Inspired by gmailr.js | |
---|---|
Kartik Talwar | See License.md |