Any time you include script from an external domain you are trusting that domain. e.g. if you site is example.com
and you have the following code on your home page
<script src="//example.edu/tracking_script.js"></script>
then example.com
is fully trusting example.edu
not to do anything malicious inside tracking_script.js
. example.edu
will have full control of client-side scripting and could do anything a client-side script hosted on example.com
could do.
The same goes with Google Analytics - you are adding the script code to your page that creates the external js
reference. If Google wanted to, they could adapt their script to do anything client-side to your pages. The same goes for a situation where Google Analytics website is compromised - any attacker will control all domains using Analytics.
Discounting anything malicious, the advantage of this to Google is that they can update the Analytics client-side code without webmasters having to do any updates on their side. So if they update a server-side function, they can update the client-side counterpart appropriately and every site in the world will automatically run the new client-side code for their visitors.
postMessage
, while it maintains a security perimeter between your domain and GA's, would not permit any client-side script updates that may be necessary for GA to function after a server-side update. (Note that you do not need an IFrame for secure cross-domain communication, CORS enabled on Google's side would allow your site to send a HTTP POST request to register each page visit.)
When using a Google product, you will be pretty safe including the script referencing - so there is little requirement for this to be done in a different manner. However, having script references to lesser known entities whose security might not be quite upto the standard of Google's may be of cause for concern. In those instances it would be prudent to rely on a more secure client-side technology rather than that of JSONP.