]> BookStack Code Mirror - api-scripts/blob - chrome-extension-google-search-results/background.js
Added bsfs to community project list
[api-scripts] / chrome-extension-google-search-results / background.js
1 // Listen to messages from our content-script
2 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
3
4
5     // If we're receiving a message with a query, search BookStack
6     // and return the BookStack results in the response.
7     if (request.query) {
8         searchBookStack(request.query).then(results => {
9             if (results) {
10                 sendResponse({results});
11             }
12         });
13     }
14
15     // Return true enables 'sendResponse' to work async
16     return true;
17 });
18
19
20 // Search our BookStack instance using the given query
21 async function searchBookStack(query) {
22
23     // Load BookStack API details from our options
24     const options = await loadOptions();
25     for (const option of Object.values(options)) {
26         if (!option) {
27             console.log('Missing a required option');
28             return;
29         }
30     }
31
32     // Query BookStack, making an authorized API search request
33     const url = `${options.baseUrl}/api/search?query=${encodeURIComponent(query)}`;
34     const resp = await fetch(url, {
35         method: 'GET',
36         headers: {
37             Authorization: `Token ${options.tokenId}:${options.tokenSecret}`,
38         }
39     });
40
41     // Parse the JSON response and return the results
42     const data = await resp.json();
43     return data.data || null;
44 }
45
46
47 /**
48  * Load our options from chrome's storage.
49  * @returns Promise<Object>
50  */
51 function loadOptions() {
52     return new Promise((res, rej) => {
53         chrome.storage.sync.get({
54             tokenId: '',
55             tokenSecret: '',
56             baseUrl: '',
57         }, options => {
58             res(options);
59         })
60     });
61 }