goly-chrome/background.js
jolheiser 1b640d2c1a
Better errors and status checking
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-07-10 22:11:07 -05:00

66 lines
1.7 KiB
JavaScript

let client = new Client();
chrome.storage.sync.get(['golyBaseUrl'], (result) => {
client = new Client(result.golyBaseUrl);
checkStatus();
});
chrome.runtime.onMessage.addListener((msg) => {
if (msg.url !== undefined) {
client = new Client(msg.url);
checkStatus();
}
});
chrome.contextMenus.onClicked.addListener((info) => {
if (info.menuItemId === 'goly-short') {
client.setLink({url: info.linkUrl}).then(link => {
copy(`${client.baseURL}/${link.short}`);
alert('Short link copied');
}).catch(err => {
alert(JSON.stringify(err));
});
}
});
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
client.setLink({url: tabs[0].url}).then(link => {
copy(`${client.baseURL}/${link.short}`);
alert('Short link copied');
}).catch(err => {
alert(JSON.stringify(err));
});
})
});
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
type: 'normal',
id: 'goly-short',
title: 'Shorten this link',
contexts: ['link'],
});
});
function copy(str) {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
function checkStatus() {
client.getStatus().then((status) => {
if (status.version === '') {
alert('Invalid Goly base URL.');
return;
}
alert(`Connected to Goly v${status.version}\n${client.baseURL}`);
}).catch((err) => {
alert(err);
});
}