Skip to content

Instantly share code, notes, and snippets.

@mattduggan
Last active November 14, 2018 14:25
Show Gist options
  • Save mattduggan/c2d2bfbcb77559092a897af11ee46dad to your computer and use it in GitHub Desktop.
Save mattduggan/c2d2bfbcb77559092a897af11ee46dad to your computer and use it in GitHub Desktop.
Convert from legacy to perm thread id
// background.js
// memoize thread ids
const threadIds = {};
// register redirect handler to capture perm thread ids
function memoizePermThreadId(details) {
const originalUrl = new URL(details.url);
if (originalUrl.searchParams.has('idr')) {
var legacyThreadId = decodeURIComponent(originalUrl.searchParams.get('idr')).split('/')[1];
var redirectUrl = new URL(details.redirectUrl);
var permThreadId = decodeURIComponent(redirectUrl.hash.split('/')[1]).substring(1); // cut off leading hash #
threadIds[legacyThreadId] = permThreadId;
}
}
chrome.webRequest.onBeforeRedirect.addListener(
memoizePermThreadId,
{
urls: ['https://mail.google.com/*'], // filter: ajax requests to gmail
types: ['xmlhttprequest']
},
['responseHeaders']
);
// register message handler to get perm thread id from legacy thread id
function fetchPermThreadId(request, sender, sendResponse) {
if (request.message === 'gmail::thread::fetch_perm_thread_id') {
if (threadIds.hasOwnProperty(request.legacyThreadId) {
sendResponse(threadIds[request.legacyThreadId]);
} else {
var gmailUrl = new URL(sender.url); // important this comes from Gmail for multi-user accounts
var permThreadIdUrl = new URL(gmailUrl.protocol + gmailUrl.hostname + gmailUrl.pathname);
permThreadIdUrl.searchParams.set('idr', 'all/' + request.legacyThreadId); // using `all` label
fetch(permThreadIdUrl, { method: 'HEAD', mode: 'cors' })
.then(function() { sendResponse(threadIds[request.legacyThreadId]); }); // by this point, onBeforeRequest has memoized the perm thread id
}
}
return true; // async
}
chrome.runtime.onMessage.addListener(fetchPermThreadId);
// gmail.js
function navigateToThread(legacyThreadId) {
chrome.runtime.sendMessage(
{ message: 'gmail::thread::fetch_perm_thread_id', legacyThreadId }, // must be hex, not decimal
function(permThreadId) {
window.location.hash = '#all/' + permThreadId;
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment