-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
53 lines (48 loc) · 1.78 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
'use strict';
const tokenURL = 'https://account.kkbox.com/oauth2/token';
const baseSearchURL = 'https://api.kkbox.com/v1.1/search';
const grantType = 'client_credentials';
const clientId = '3ac701a5aecd9339a0a59d1b48121909';
const clientSecret = 'aa6f4336f75d183d6a95bb0d4cbe8ed4';
const functions = ['track', 'album', 'artist', 'playlist'];
chrome.runtime.onInstalled.addListener(function() {
for (let f of functions) {
chrome.contextMenus.create({
id: f,
title: 'Find music by ' + f,
type: 'normal',
contexts: ['selection'],
});
}
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
let type = info.menuItemId;
let keywords = info.selectionText;
let queryString = `grant_type=${grantType}&client_id=${clientId}&client_secret=${clientSecret}`;
let xhr = new XMLHttpRequest();
xhr.open('POST', tokenURL);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let kkAPIToken = xhr.response.access_token;
let searchURL = baseSearchURL + `?q=${keywords}&type=${type}&territory=TW&limit=5`;
xhr.open('GET', searchURL);
xhr.setRequestHeader('Authorization', 'Bearer ' + kkAPIToken);
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let result = xhr.response;
if (result.summary.total > 0) {
// chrome.tabs.sendMessage(tab.id, {data: result, type: 'result'});
alert(JSON.stringify(xhr.response));
} else {
alert('Nothing match!');
}
}
}
xhr.send();
}
};
xhr.send(queryString);
});