Skip to content

Commit

Permalink
Initial implementation of DuckDuckGo Instant answer (#44)
Browse files Browse the repository at this point in the history
* Initial implementation of DuckDuckGo Instant answer

* Minor fixes and results in new category

* Dummy catch duckduckgo API errors

* Improve formatting and cases prone to errors

* Fix missing icons

Co-authored-by: blenderskool <[email protected]>
  • Loading branch information
blenderskool authored Nov 15, 2020
2 parents a82747a + a931cad commit f9af3ad
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
53 changes: 49 additions & 4 deletions src/background/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,55 @@ export default {
displayName: 'DuckDuckGo search',
match: /\s*(.*?)/,
keys: [ 'd', 'duckduckgo' ],
item: {
favicon: 'https://duckduckgo.com/favicon.ico',
title: 'Search DuckDuckGo for $1',
url: 'https://duckduckgo.com?q=$1',
async item(query) {
const results = [];

if (query.length > 3) {
const category = 'Instant answer';
const parseIconUrl = (url) => {
if (!url || url === '') return;
return url.indexOf('http') === 0 ? url : 'https://duckduckgo.com' + url;
};

try {
const search = await fetch(`https://api.duckduckgo.com/?q=${encodeURI(query)}&format=json`).then(response => response.json());

if (search.Abstract) {
results.push({
favicon: parseIconUrl(search.Image),
title: search.AbstractText,
url: search.AbstractURL,
category,
});
}

results.push(...search.Results.map(result => ({
favicon: parseIconUrl(result.Icon?.URL),
title: result.Text,
url: result.FirstURL,
category,
})));

results.push(
...search.RelatedTopics
.filter(topic => !!topic.FirstURL)
.map(topic => ({
favicon: parseIconUrl(topic.Icon?.URL),
title: topic.Text,
url: topic.FirstURL,
category,
}))
);
} catch {}
}
return [
{
favicon: 'https://duckduckgo.com/favicon.ico',
title: 'Results from DuckDuckGo for $1',
url: 'https://duckduckgo.com?q=$1',
},
...results,
];
},
handler(item, sendResponse) {
chrome.tabs.create({ active: true, url: item.url }, () => sendResponse());
Expand Down
3 changes: 2 additions & 1 deletion src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"history",
"bookmarks",
"chrome://favicon/",
"storage"
"storage",
"https://api.duckduckgo.com/*"
],
"content_security_policy": "script-src 'self'; object-src 'self'; img-src http: https: data: chrome://favicon;"
}

0 comments on commit f9af3ad

Please sign in to comment.