function onResponse(response) { console.log(`Received ${response}`); } function onError(error) { console.log(`Error: ${error}`); } async function handleClick(tab) { const gldata = await parsetab(tab.id); browser.runtime.sendNativeMessage("ping_pong", gldata) .then(onResponse, onError); } async function parsetab(tabId) { const tab = browser.tabs.get(tabId); var data = { host: null, repo: null, file: null, branch: null }; // try to find the Clone button to determine if we're in a root repo // Clone const hasClone = await tab.then(async function(tab) { const txt = await browser.tabs.executeScript(tab.id, { code: 'document.querySelector(".js-clone-dropdown-label").innerText' }).then(function(result) { if (!result) { throw new Error("No result"); } return result[0]; }).catch(function() { return ''; }); if (txt && txt === 'Clone ') { return true; } return false; }); // try to find the Blame button to determine if we're in a file inside a repo const hasBlame = await tab.then(async function(tab) { const txt = await browser.tabs.executeScript(tab.id, { code: 'document.querySelector(".js-blob-blame-link").innerText' }).then(function(result) { if (!result) { throw new Error("No result"); } return result[0]; }).catch(function() { return ''; }); if (txt && txt === 'Blame') { return true; } return false; }); // if we're not in a repo, or file within a repo, bail out if (!hasClone && !hasBlame) { return data; } const url = await tab.then(function(tab) { return new URL(tab.url); }); data.host = url.hostname; // if we're in a root repo, the repo path should be the original url removing // the hostname and leading slash if (hasClone && !hasBlame) { data.repo = url.pathname.substring(1); // if we're in a file, resort to a regex match } else if (!hasClone && hasBlame) { data.repo = url.pathname.match(/^\/(.*)\/-/)[1]; data.branch = url.pathname.match(/^\/.*\/-\/blob\/(.*)\//)[1]; data.file = url.pathname.match(/^^\/.*\/-\/blob\/.*\/(.*)(\?)?/)[1]; if (!data.repo) { throw new Error("Could not find repo"); } else if (!data.branch) { throw new Error("Could not find branch"); } else if (!data.file) { throw new Error("Could not find file"); } } else { throw new Error("Unknown state"); } return data; } browser.pageAction.onClicked.addListener(handleClick);