From d72830b76237945f6dea67525e1bee3b923721a1 Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Mon, 17 Oct 2022 23:35:53 -0700 Subject: [PATCH] Fast tab close, upload screenshot attachment --- background.js | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/background.js b/background.js index fa15dc5..1992f9b 100644 --- a/background.js +++ b/background.js @@ -1,3 +1,5 @@ +const reData = new RegExp('^data:(.*?);base64,(.*)$'); + async function handleClick() { const tabs = await browser.tabs.query({currentWindow: true, active: true}); if (tabs.length != 1) { @@ -5,6 +7,8 @@ async function handleClick() { } const tab = tabs[0]; + const promiseImgURL = browser.tabs.captureTab(tab.id); + const cfg = await browser.storage.sync.get(); const req = { data: { @@ -16,8 +20,6 @@ async function handleClick() { }; console.log('-->', req); - const promiseImg = browser.tabs.captureTab(tab.id); - const promiseCreateResp = fetch( 'https://app.asana.com/api/1.0/tasks', { @@ -31,13 +33,42 @@ async function handleClick() { }, ); - const img = await promiseImg; + const imgURL = await promiseImgURL; + const [_, imgType, imgBase64] = imgURL.match(reData); + const img = atob(imgBase64); + + // All tab info captured + browser.tabs.remove([tab.id]); + const createResp = await promiseCreateResp; const create = await createResp.json(); console.log('<--', create); - browser.tabs.remove([tab.id]); + const imgBytes = new Uint8Array(img.length); + for (let i = 0; i < img.length; i++) { + imgBytes[i] = img.charCodeAt(i); + } + const blob = new Blob( + [imgBytes], + { + type: imgType, + }, + ); + + const data = new FormData(); + data.append('file', blob, 'screenshot.png'); + + const attachResp = await fetch( + `https://app.asana.com/api/1.0/tasks/${encodeURIComponent(create['data']['gid'])}/attachments`, + { + method: 'POST', + headers: { + 'Authorization': `Bearer ${cfg['token']}`, + }, + body: data, + }, + ); } browser.browserAction.onClicked.addListener(handleClick);