A) The browser stops JavaScript code retrieved from a website making GET requests to another website such as Facebook, because some websites store sessions(logged in), when you make a GET request from that website, you can capture the session cookie, which obviously is a no-no. |
More precisely, if Javascript code on web-site X would be allowed to make arbitrary requests (e.g. via XMLHttpRequest) to an unrelated web-site Y, then your web-browser would send any cookies that were previously created by web-site Y along with those requests. Web-site X never "sees" those cookies! Nonetheless, if the cookie contains something like a
session ID, which is a typical use-case for cookies, then to web-site Y those requests would seem like legitimate requests originating from
your session (user account), even though the request was in fact created by the JavaScript code from web-site X – and therefore is fully under the control of web-site X.
Example: The JavaScript code on the web-site "evil.com" would be able to create new posts at the "cplusplus.com" forum under
your user account – provided that you have an active session at "cplusplus.com". This could happen totally hidden, when you visit "evil.com".
I think this is
not limited to GET requests, but effects, e.g., POST requests too.
The
same origin policy prevents this kind of cross-site request forgery (CSRF) attacks. There are other anti-CSRF techniques too.
B) The browser also stops you from accessing the document and (most) code from inside iframes. By doing this, even if we create a malicious site that has a hidden iframe with Facebook or even a banking site, and assuming we are logged into that website in another tab or have a logged in session. This prevents us from accessing critical data inside this iframe's document such as submitting a form or even stealing the cookies. |
Web-sites set the
X-Frame-Options
header to indicated whether embedding in
<iframe>
s on other web-sites should be allowed.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
C) There are ways around this, by using HTML elements, such as; <form>,<img> tags. |
<img>
and
<form>
are
not restricted by the same origin policy. I think this is mostly for "legacy compatibility" reasons.
An API server could easily "block" GET or POST requests generated via HTML
<form>
, simply by requiring a
custom header in the request. Requests lacking the custom header would be discarded by the server. With HTML
<form>
it is
not possible to add a custom header to the requests! XMLHttpRequest
can add custom headers to the request, but with XMLHttpRequest the same origin policy kicks in 😏