Adding Google Custom Search to AMP site

孤街浪徒 提交于 2020-07-06 11:24:51

问题


I have my Google Custom Search Engine (GCSE) code:

<script>
  (function() {
    var cx = '008589157460623253837:mhsjluzrngo';
    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>

However my Accelerated Mobile Pages (AMP) site does not allow me to add JavaScript to it, and I don't see any AMP components that allow for embedding GCSE into an AMP site.

How can I get GCSE on my site without breaking AMP compliance?

Thanks


回答1:


You can try putting that code in a separate page then including that page in your AMP via the amp-iframe component. You will also have to abide by the constraints described here: https://www.ampproject.org/docs/reference/components/amp-iframe




回答2:


You're correct, this is not supported yet as it is not in the AMP Components list. Try to file a feature request on their githubpage.




回答3:


I added a search feature to my open source website (https://csaba.page/) with amp-form following these steps:

  1. Create a GCSE (Google Custom Search Engine) at the CSE (Custom Search Engine) Console https://cse.google.com/ as described by https://developers.google.com/custom-search/docs/tutorial/creatingcse if you haven't already done so.
  2. Remember your Search engine ID, it looks something like "013535696182405026577:kmxne16xdtx". You can see it on the Basics tab in the CS Console, or if you are looking at the JavaScript code it's the cx variable.
  3. Add <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script> to your head section where the other AMP includes are.
  4. In the body add an amp-form where you want to position the search input and style the form as you need:
<div>
  <form method="GET" class="search-form" action="https://www.google.com/cse" target="_top">
    <div class="search-form-inner">
      <input name="cx" type="hidden" value="013535696182405026577:kmxne16xdtx" />
      <input name="ie" type="hidden" value="UTF-8" />
      <input type="search" placeholder="Search..." name="q" required>
      <input type="submit" value="Go" class="search-button">
    </div>
  </form>
</div>

Here are some blog posts as well:

  • https://csaba.page/blog/amp-google-custom-search-engine.html
  • https://gfw-blog.netlify.app/2018/05/11/cse-amp.html

And an initial commit: https://gitlab.com/MrCsabaToth/mrcsabatoth.gitlab.io/-/commit/96345716d620b916d1c61cb5b51941378ffc5dc6



来源:https://stackoverflow.com/questions/42989081/adding-google-custom-search-to-amp-site

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!