Adding Google Custom Search to AMP site

GFW VPN
1 min readMay 11, 2018

--

If you set up a Google Custom Search for your website, you will get some JavaScript code. But Accelerated Mobile Pages (AMP) site does not allow to add JavaScript to AMP site.

TL;DR

  • Find your Search engine ID from JavaScript code.
  • Use AMP amp-form Component, and submit the form to Google Custom Search.
  • valid your AMP page.

1. Search engine ID

When you get JavaScript code from Google Custom Search, you can find your engine ID.

<script>
(function() {
var cx = '005682938207833448670:tg4ixgq0iyi';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>

The value of cx is your engine ID, the above engine ID is

005682938207833448670:tg4ixgq0iyi

2. amp-form Component

Copy the following code, and paste it into <head> section

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

Copy the following code, and paste it into <body> section

<div> <form method="GET" class="p2" action="https://www.google.com/cse" target="_top"> <div class="ampstart-input inline-block relative mb3"> <input name="cx" type="hidden" value="005682938207833448670:tg4ixgq0iyi" /> <input name="ie" type="hidden" value="UTF-8" /> <input type="search" placeholder="Search..." name="q" required> <input type="submit" value="Go" class="search-links"> </div> </form> </div>

replace the engine ID (005682938207833448670:tg4ixgq0iyi) into yours

3. AMP page valid

AMP valid

Originally published at gfw-blog.netlify.com on May 11, 2018.

--

--

GFW VPN
GFW VPN

Written by GFW VPN

https://gfw.netlify.app 为中国用户提供vpn服务.join our network, rule your own internet

No responses yet