-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
84 lines (69 loc) · 2.14 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
chrome.contextMenus.onClicked.addListener(contextClick)
async function getCurrentTab() {
let queryOptions = {active: true, currentWindow: true};
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
function injectedFunction_egrave(text) {
let input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
document.execCommand("copy");
input.remove();
}
function copyToClipboard(text) {
console.log(text);
getCurrentTab().then(function (tab) {
chrome.scripting.executeScript({
target: {tabId: tab.id},
args: [text],
function: injectedFunction_egrave
});
});
}
chrome.runtime.onInstalled.addListener(function () {
chrome.contextMenus.create({
"id": "create_bitly_form_selection",
"title": "Shorten selection and copy to clipboard",
"contexts": ["selection"],
});
chrome.contextMenus.create({
"id": "create_bitly_from_link",
"title": "Shorten link and copy to clipboard",
"contexts": ["link"],
});
});
function contextClick(info) {
const {menuItemId} = info
if (menuItemId === 'create_bitly_form_selection') {
shorten(info['selectionText'])
}
if (menuItemId === 'create_bitly_from_link') {
shorten(info['linkUrl'])
}
}
function shorten(text) {
if (text == "")
return;
copyToClipboard('Shortening, please wait a while...');
chrome.storage.sync.get(['token'], function (result) {
const token = result.token;
if (token == null) {
copyToClipboard('Please set your token in the options page');
}
fetch('https://api-ssl.bitly.com/v4/shorten', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify({"long_url": text, "domain": "bit.ly"})
}).then((data) => {
data.json().then((json) => {
copyToClipboard(json.link)
})
})
});
}