隐藏Google自定义搜索元素API 2.0的搜索引擎ID

Hide Search Engine ID for Google Custom Search Element API 2.0

本文关键字:搜索引擎 ID API Google 自定义 搜索 元素 隐藏      更新时间:2023-09-26

我正在ASP.NET MVC项目中实现Google Custom Search Element API 2.0。在文档中,他们要求在视图中包含以下javascript,并在其后包含<gcse:search>元素。

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

然而,搜索引擎id在以下行中可见:

var cx = 'xxxxxxxx:yyyyyyyy';

在浏览器中,选择View Source(或类似内容)允许用户查看脚本和搜索引擎id。

我如何确保没有人能看到我的身份证?

我找到了解决这个问题的方法。通过将谷歌脚本移动到其自己的函数,该函数将搜索引擎Id作为参数:

function buildSearchElement(cx)
{
    var gcse = document.createElement("script");
    gcse.type = "text/javascript";
    gcse.async = true;
    gcse.src = (document.location.protocol === "https:" ? "https:" : "http:") +
        "//www.google.com/cse/cse.js?cx=" + cx;
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(gcse, s);
};

然后,我在控制器上调用一个方法,该方法在页面加载时返回搜索引擎Id。完成后,回调为buildSearchElement函数:

(function ()
{
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function()
    {
        if (httpRequest.readyState === 4 && httpRequest.status === 200)
        {
            buildSearchElement(httpRequest.responseText);
        }
    }
    httpRequest.open("GET", "/GetSearchElementId");
    httpRequest.send();
})();