]> BookStack Code Mirror - api-scripts/blob - chrome-extension-google-search-results/content-script.js
Added the Flutter/Dart example (#12)
[api-scripts] / chrome-extension-google-search-results / content-script.js
1 const url = new URL(window.location.href);
2 const query = url.searchParams.get("q");
3 const resultContainer = document.getElementById('search');
4
5 // If we have a query in the URL, and a '#search' section, we are 
6 // likely on a search results page so we kick-off the display of 
7 // results by messaging the back-end to make the request to BookStack.
8 if (query && resultContainer) {
9
10     chrome.runtime.sendMessage({query}, function(response) {
11         // If re receive results back from our background script API call,
12         // show them on the current page.
13         if (response.results) {
14             showResults(response.results);
15         }
16     });
17
18 }
19
20 /**
21  * Display the given API search result objects as a list of links on 
22  * the current page, within the '#search' section.
23  * @param {Object[]} results 
24  */
25 function showResults(results) {
26     const resultHTML = results.map(result => {
27         return `
28         <a href="${result.url}">
29             <h3>${result.type.toUpperCase()}: ${result.preview_html.name}</h3>
30             <p style="color: #444; text-decoration: none;font-size:0.8em;">${result.preview_html.content}</p>
31         </a>
32         `;
33     }).join('\n');
34
35     const header = `<h4>BookStack Results</h4>`;
36     const container = document.createElement('div');
37     container.innerHTML = header + resultHTML + '<hr>';
38     resultContainer.prepend(container);
39 }