How does Google's javascript API get around the cross-domain security in AJAX

一笑奈何 提交于 2019-11-28 19:41:42

They get around it by dynamically injecting script tags into the head of the document. The javascript that is sent down via this injection has a callback function in it that tells the script running in the page that it has loaded and the payload (data).

The script can then remove the dynamically injected script tag and continue.

The accepted answer is wrong. Ben is correct. Below is the actually iframe node pulled off a page using the Google API JavaScript Client.

<iframe name="oauth2relay678" id="oauth2relay678" 
        src="https://accounts.google.com/o/oauth2/postmessageRelay?
             parent=https%3A%2F%2Fwww.example.com.au#rpctoken=12345&amp;forcesecure=1" 
             style="width: 1px; height: 1px; position: absolute; left: -100px;">
</iframe>

Basic summary of how this works is here: http://ternarylabs.com/2011/03/27/secure-cross-domain-iframe-communication/. On modern browsers they utilize HTML postMessage to achieve communication, and on older browsers, they use a neat multiple-iframe-urlhash-read+write-combination hack. Ternary Labs have made a library which abstracts all the hacky stuff out, essentially giving you postMessage on all browsers.

One day I'll build ontop of this library to simplify cross-domain REST APIs...

Edit: That day has come and XDomain is here - https://github.com/jpillora/xdomain

AFAIK they use IFRAMEs.

Another possibility is to use the window.name transport as described for the dojo framework here

Looks like Google display maps using the <img> tag I guess they use the JavaScrit library to work out all the co-ordinates and other parameters the src url needs, then insert the <img> tags (along with a million other tags) into your DOM.

The full map is built up with several panes like the HTML below:

<img src="https://mts1.google.com/vt/lyrs=m@248102691&hl=en&src=app&x=32741&s=&y=21991&z=16&scale=1.100000023841858&s=Galile" class="css-3d-layer" style="position: absolute; left: 573px; top: 266px; width: 128px; height: 128px; border: 0px; padding: 0px; margin: 0px;">

(You can paste this HTML into your own web page to see the result)

So Google Maps does NOT use AJAX or anything to get its maps, just plain images, created on the fly. So no Cross Domain issues to worry about...

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