【问题标题】:Add a custom search engine via JavaScript通过 JavaScript 添加自定义搜索引擎
【发布时间】:2014-02-07 02:04:59
【问题描述】:

我正在尝试创建一个非常简单的站点,该站点使用Google Charts QR API 生成二维码。我用的代码很简单

<form id="QR" action="http://chart.apis.google.com/chart" target="QRwindow" method="POST">
  <h1>QR Code<br/>Generator</h1>
  <textarea autofocus name="chl"
  onkeypress="if(event.which==13&&!event.shiftKey){document.getElementById('cht').click();event.preventDefault();}"
  onkeyup="if(this.value.length&gt;2000) this.value=this.value.substring(0,1500)"></textarea>
  <div>QR size (px):</div>
  <input type="hidden" name="chld" value="|0"/>
  <input type="number" name="chs" value="250" min="50" max="275"/>
  <button type="submit" name="cht" id="cht" value="qr">Generate!</button>
</form>
<iframe name="QRwindow" id="QRwindow" width="275" height="275" frameborder="0" src="http://chart.apis.google.com/chart?chld=|0&chs=250&cht=qr&chl=Foo%20Bar"></iframe>

http://jsbin.com/fule/2/

我想做的是添加一个按钮,自动让用户使用以下网址添加搜索引擎:

http://chart.apis.google.com/chart?chld=|0&chs=250&cht=qr&chl=%s

但我找不到任何自动为用户添加搜索引擎的方法。我当然理解这可能是一个安全风险,但也有可能为mailto: 添加处理程序 gmail,所以我想像添加搜索引擎这样的类似浏览器设置是可能的(是得到用户的确认)。这可能吗?

【问题讨论】:

    标签: javascript html search-engine


    【解决方案1】:

    您可以通过使用搜索引擎信息创建一个 xml 文档来做到这一点,并添加:

    window.external.AddSearchProvider('/linktoyourxmldoc.xml')
    

    您的 XML 应具有以下属性:

    <?xml version='1.0' encoding='UTF-8'?>
    <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
        <ShortName>QR creator</ShortName>
        <Description>Create a QR code.</Description>
        <Tags>qr</Tags>
        <Contact>youremail@email.com</Contact>
        <Url type="text/html" template="http://chart.apis.google.com/chart?chld=|0&amp;chs=250&amp;cht=qr&amp;chl={searchTerms}"/>
    </OpenSearchDescription>
    

    我还没有让它在 chrome 中工作。

    编辑: 它不起作用,您需要将 & 符号更改为 &amp;amp;

    这都是根据opensearch standard。更多搜索选项和信息在this 页面上。

    我不知道为什么它不能在 chrome 中工作,因为 this 文档指出它也可以在 chrome 中工作。

    还有seems,你可以直接在你的标题中放一个链接:

    <link rel="search" type="application/opensearchdescription+xml" href="/linktoyourxmldoc.xml" title="MySite Search" />
    

    【讨论】:

    • 哪些浏览器支持这个?你有任何关于这方面的更多信息的参考吗?
    • this JSBin works in Chrome。问题可能是脚本中的内容类型不是application/opensearchdescription+xml(显然具有文件扩展名.osdx),而是text/xml。在 Firefox 中,它说不支持搜索引擎,在 IE 中它返回一个错误,说 window.external 未定义,但手动运行脚本返回一个错误,说 permission denied。最后,Opera 就是不支持它。我没有测试 Safari。
    • @Joeytje50 在 Chrome 46 中似乎不适合我
    • @Alex jsbin 似乎由于某种原因消失了。我猜那个链接坏了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多