Prevent queries without keywords
Prevent queries without keywords
By default, submitting a query without entering any keywords in the search box allows the end user to retrieve a list of currently trending result items.
However, you may rather want to hide all search interface components except the search box until the end user submits their first non-empty query, and essentially ignore empty queries thereafter.
Current framework version
Since the February 2018 release (v2.2826.10) of the JavaScript Search Framework, preventing empty queries in a search page is trivial: all you have to do is set the allowQueriesWithoutKeywords option of your SearchInterface component to false.
<div id="search" class="CoveoSearchInterface" data-allow-queries-without-keywords="false">
<!-- ... -->
</div>
Previous framework versions
If you’re using a JavaScript Search Framework version prior to the February 2018 release (v2.2826.10), you can insert the following code sample between the endpoint registration (for example, Coveo.SearchEndpoint.configureCloudV2Endpoint(...)) and framework initialization (for example, Coveo.init(...)) top-level function calls of your search page to prevent queries without keywords:
function hidePage() {
togglePageVisibility(false);
}
function togglePageVisibility(show) {
Coveo.$$(document).find('.coveo-search-section').style.marginTop = show ? null : '20%';
Coveo.$$(document).find('.coveo-main-section').style.display = show ? null : 'none';
Coveo.$$(document).find('.coveo-tab-section').style.visibility = show ? 'visible' : 'hidden';
}
function executeNonEmptyQuery(e, data) {
let root = Coveo.$$(document).find("#search")
if (Coveo.state(root, "q").length > 0) {
Coveo.executeQuery(root);
}
}
function showPage(e, data) {
if (data.queryBuilder.containsEndUserKeywords()) {
togglePageVisibility(true);
} else {
let root = Coveo.$$(document).find("#search");
let queryController = Coveo.get(root, "QueryController");
let lastBasicQueryExpression = queryController.lastQuery ? queryController.lastQuery.q : undefined;
if (lastBasicQueryExpression) {
data.queryBuilder.expression.add(lastBasicQueryExpression);
Coveo.state(root, "q", lastBasicQueryExpression);
}
}
}
let root = Coveo.$$(document).find('#search');
Coveo.$$(root).on('beforeInitialization', hidePage);
Coveo.$$(root).on('afterInitialization', executeNonEmptyQuery);
Coveo.$$(root).on('doneBuildingQuery', showPage);
|
|
Note
If the root element of your search interface doesn’t have For example:
|
When using the above code sample, you should also set the autoTriggerQuery option of your SearchInterface component to false.
<div id="search" class="CoveoSearchInterface" data-auto-trigger-query="false">
While leaving this option to true has no noticeable visual effect, it nevertheless results in a useless query being executed when the page is first initialized.
|
|
Note
If you’re using a JavaScript Search Framework version prior to the July 2018 release (v2.2900.23), you must also set the
|