1

Can I search Google with a cross-origin XMHhttpRequest()?

var xhr = XMLHttpRequest();
xhr.open("GET", www.google.com/?q=what+you+want+to+search, true);
Luke
  • 13,678
  • 7
  • 45
  • 79
Rohan A
  • 97
  • 3
  • 11
  • 3
    Read about the [Same Origin Policy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript) and understand why it is not going to happen. If you want to search google, use their [API](https://developers.google.com/custom-search/v1/overview). – epascarello Jun 21 '13 at 17:44
  • google chrome extensions apparently can send cross-origin XMLHttpRequests. I wanted to know if the code I wrote is a method that would work. – Rohan A Jun 21 '13 at 17:59
  • @RohanA By running the code and you would have figured out if it worked. – epascarello Jun 21 '13 at 18:04

1 Answers1

1

Try it:

curl -H "Origin: http://domain.com" -X OPTIONS --head https://www.google.com/

This currently gives you:

HTTP/1.1 405 Method Not Allowed
Content-Type: text/html; charset=UTF-8
Content-Length: 962
Date: Fri, 21 Jun 2013 17:58:45 GMT
Server: GFE/2.0

So no, you can't, at least not with their public facing website. There would be an Access-Control-Allow-Origin: * in there if that was the case, with a 200 OK. The * is a wildcard for "any domain". So it would either have to be this, or it would have to match your origin.

Even if it did return the correct header, you have to have CORS support in the browser. You can see browser compatibility here. IE 8 and 9 only supports CORS through XDomainRequest, which has heavy restrictions (no cookies, or custom headers, for example). You can read more about access control headers here.

When CORS fails, same origin policy is used.

There is a way though. The Google REST API does support cross origin requests:

curl -H "Origin: http://domain.com" -X GET --head "https://www.googleapis.com/customsearch/v1?"

Which gives you:

HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: http://domain.com
Content-Type: application/json; charset=UTF-8
Access-Control-Expose-Headers: Content-Encoding,Content-Length,Content-Type,Server
Date: Fri, 21 Jun 2013 18:12:51 GMT
Expires: Fri, 21 Jun 2013 18:12:51 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Transfer-Encoding: chunked

Notice the Access-Control-Allow-Origin: http://domain.com.

So assuming you have an API key, you can, if you use the API.

Luke
  • 13,678
  • 7
  • 45
  • 79