This question came up recently across a Coveo project we working on so I'll quickly share it.
The easiest way to retrieve the value of the query is through Coveo's State model. State is used to retrieve and update settings across all of the components. One of which are the current search terms.
Get Current Query
// The ID of your root Coveo search interface element
var searchRoot = document.querySelector("#search");
var query = Coveo.state(searchRoot, 'q')
Very straight forward. Coveo.state looks through key-value pairs associated with the search and returns the value mapped to q.
Change Current Query
// The ID of your root Coveo search interface element
var searchRoot = document.querySelector("#search");
var query = Coveo.state(searchRoot, 'q', 'different keywords')
Updating the query in this way will also update the values entered in your Querybox.
Speaking of which - instead of referencing your Coveo search interface element, you can reference your Querybox or Searchbox component directly with the same syntax.
Using buildingQuery Event to Change Query
document.addEventListener('DOMContentLoaded', function () {
// initialize Coveo if it hasn't happened yet
// Coveo.init(document.getElementById('search'));
var searchRoot = document.querySelector("#search");
searchRoot.addEventListener('buildingQuery', function(e) {
Coveo.state(searchRoot, 'q', 'different keywords');
});
});
Again, updated the state will update the search terms across all the search inputs. If you want to change the terms but not your input, here is a more radical option that works. Which is all I can say as far as endorsing it.
Changing Query Without Updating Inputs
document.addEventListener('DOMContentLoaded', function () {
// initialize Coveo if it hasn't happened yet
// Coveo.init(document.getElementById('search'));
var searchRoot = document.querySelector("#search");
searchRoot.addEventListener('doneBuildingQuery', function(e) {
e.detail.queryBuilder.expression.parts[0] = "overriding keywords"
});
});
So if the query was "dogs", the interface would continue to display "dogs" but the query sent to the server would be for "overriding keywords".
Note this is happening in the doneBuildingQuery event. One event down the line from buildQuery. We're only wanting to modify the query after it's finished being built.
If this path approach was to be taken, I'd recommend to first read the the value from q, then loop through the parts[] array to find a match, then replace the matching value at the found index.
Coveo When Using jQuery
$("#search").coveo('state', 'q', 'different keywords');
If you're using Coveo for Sitecore or jQuery you may find yourself using the above syntax. In this method, Coveo is mounted as a jQuery plug-in.
There is a lot more to dig into with Coveo's JavaScript. Even if you fancy yourself doing a Coveo for Sitecore or Coveo for Salesforce implementation I'd recommend reading the Coveo JavaScript Framework walk-through.