The Same-Origin Policy

There is one far-reaching security restriction in JavaScript that deserves its own section. This restriction is known as the same-origin policy: a script can read only the properties of windows and documents that have the same origin (i.e., that were loaded from the same host, through the same port, and by the same protocol) as the script itself.

The same-origin policy does not actually apply to all properties of all objects in a window from a different origin. But it does apply to many of them, and in particular, it applies to practically all of the properties of the Document object. For all intents and purposes, you should consider all predefined properties of all client-side objects with different origins off-limits to your scripts. User-defined properties of objects with different origins may also be restricted, although this may vary from implementation to implementation.

The same-origin policy is a fairly severe restriction, but it is necessary to prevent scripts from stealing proprietary information. Without this restriction, an untrusted script (perhaps a script loaded through a firewall into a browser on a secure corporate intranet) in one window could use DOM methods to read the contents of documents in other browser windows, which might contain private information.

Still, there are circumstances in which the same-origin policy is too restrictive. It poses particular problems for large web sites that use more than one server. For example, a ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.