Thursday, 7 August 2014

Trying to update website search page

The vast majority of today was spent trying to update the search page on my photo website so that the google search results would fit okay on a small screen.

The issue was that although you can use a javascript variable (window['googleSearchFrameWidth']) to set the width of the iframe that the search results are displayed in, Google wasn't actually respecting this value. After reading various forum threads / blog posts, I tried a few things and got a better result. But the results were still about 400px or so wide. And since the results were being displayed in an iframe on a different domain, there was no way to get the width below this.

Then I discovered that there is a new Google Custom Search, which does scale automatically to fit on small screens. After implementing this on the search page, I tried to see if there was a way to have the search box on other pages as well, but always display the results on the search page. (By default the results are displayed below the search box). However, I couldn't see anyway to do this.

So instead I decided to have a fake search box on each page that would submit the search to the search page. Then I used some js on the search page to grab the submitted search query and programatically add it to the google search box on the search page and click the search button. This way a search box can be used on any page, and the results will appear on the search page.

However, I noticed in the console a message saying that it looks like I'm trying to do a search programatically and should consider using instead. Well, the first thing I thought was how clever it was of Google to detect that, and very helpful of them to include that message. However, when I searched for it brought up documentation saying that the API is deprecated and only allows limited searches.

I then tried to see if there was a more up to date API, and there is. Actually it's the same as the search code I got for my Google Custom Search form, just with a few modifications. You can find the docs here: Custom Search Element Control API. Basically you just use <gcse:searchbox-only resultsUrl=""> on any page you want your search box to appear. When the user searches, the URL set as the resultsUrl attribute will load. On this page you include either <gcse:searchresults-only> (for results only) or <gcse:search> (for search box and results).

So most of today was wasted, and the actual solution I wanted was very easy. Still, at least I did get what I wanted in the end. (Though I do still need to do some work in styling the search form).

No comments: