the-glorious-startpage/js/search-query-send.js
Gerome Matilla 7b45ba5c2c
Quick search (#29)
* readme

* add quick search

* fix errors

* fix errors part 2
2020-06-19 10:39:25 +08:00

57 lines
1.2 KiB
JavaScript

class SearchQuerySend {
constructor() {
this._searchBox = document.querySelector('#searchBox');
this._quickSearchData = config.getQuickSearchData();
}
// Check if search query is a valid url
_isURL = u => {
let dummyInput;
if (!dummyInput) {
dummyInput = document.createElement('input');
dummyInput.setAttribute('type', 'url');
}
dummyInput.value = u;
return dummyInput.validity.valid;
}
// Open link
_OpenURL = url => {
window.location.href = encodeURI(url);
}
// Quick search
_quickSearch = query => {
const prefix = query.substring(0, query.indexOf('/') + 1);
// Checks if it's a valid quick search
if (typeof this._quickSearchData[String(prefix)] === 'undefined') {
// The prefix does not exist in the object
return false;
} else {
const webSite = this._quickSearchData[String(prefix)].urlPrefix;
const queryNoSuffix = query.substring(prefix.indexOf('/') + 1);
this._OpenURL(webSite + queryNoSuffix);
return true;
}
}
// Search query
sendQuery = () => {
const searchQuery = this._searchBox.value;
// If quick search, return
if (this._quickSearch(searchQuery)) {
return;
}
// Web search
this._OpenURL(searchEngineSettings.getSearchQueryPrefix() + searchQuery);
};
}