Joeytje50
Joeytje50

Reputation: 19112

Add a custom search engine via JavaScript

I am trying to create a very simple site that uses the Google Charts QR API to generate QR codes. The code I'm using is quite simply

<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/

What I'd like to do is add a button that automatically lets the user add the search engine with the following url:

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

but I couldn't find any way to automatically add the search engine for the user. I of course understand this could be a security risk, but there's also the possibility to add a handler gmail as for mailto:, so I'd imagine a kind-of similar browser setting like adding a search engine to be possible (be it with the user's confirmation) too. Is this possible at all?

Upvotes: 3

Views: 3385

Answers (1)

MarijnS95
MarijnS95

Reputation: 4793

You can do this by creating an xml doc with the search engine information, and add it with:

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

Your XML shall have the following attributes:

<?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>[email protected]</Contact>
    <Url type="text/html" template="http://chart.apis.google.com/chart?chld=|0&amp;chs=250&amp;cht=qr&amp;chl={searchTerms}"/>
</OpenSearchDescription>

I have not yet got this to work in chrome.

Edit: It wasn't working, you need to change the & signs to &amp;.

This is all according to the opensearch standard. More search options and info are on this page.

I don't know why it's not working in chrome, as this document states that it also works in chrome.

It also seems that you can directly put a link in your header:

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

Upvotes: 6

Related Questions