I have a question regarding a potential security issue/limitation regarding JavaScript hosted on a domain (ex: domain of a CDN, say example.com), but loaded from a website under a different domain (say, example.net).
Now imagine that the JavaScript loaded will just read/modify text in a div
with a particular id, so nothing "complicated".
An example: I have the script loaded from http://example.com/myscript.js, and executed on http://example.net/index.html: [note the different TLD!]
<!-- Page example.net/index.html -->
<script src="http://example.com/myscript.js"></script>
I know that I can't access Cookies under mysite.com from the JavaScript, but I can access all the DOM on the page and in case, modify it. Isn't this a possible security issue? Shouldn't this trigger the same-origin-policy protection?
Are there user agents that prevents a JavaScript hosted on a different domain to access elements in the page that executes the script?
And, moreover, will the example above work also on HTTPS pages? (ex: https://example.net/index.html loads the script from https://example.com/myscript.js)
All URL based security restrictions in client side JavaScript are based on the URL of the webpage containing the <script>
element which loads the JS.
The URL the JS itself is hosted at is irrelevant.
Now, I know that I can't access Cookies under mysite.com from the JS.
The script is loaded into example.net
and hosted on example.com
. It can read cookies from example.net
. It cannot read cookies from example.com
. (Server side code on example.com
could dynamically generate the JavaScript and embed data taken out of cookies though).
But, I can access all the DOM on the page, and, in case, modify it.
Yes
Isn't this a possible security issue? Shouldn't this trigger the same-origin-policy protection?
It is a potential security issue, but it should not trigger the Same Origin Policy.
By loading the script, the author of the page is trusting the site hosting the script.
Do not embed JS from sites you do not trust.
And, moreover, will the example above work also on HTTPS pages? (ex:
https://example.net/index.html
loads the script fromhttps://example.com/myscript.js
)
URLs with different schemes have different origins, just as URLs with different hostnames. The Same Origin Policy rules are the same as they are based on origin not particular features of origins.
Sometimes you will get additional restrictions where a page loaded over HTTPS will be forbidden from accessing content loaded over HTTP since that breaks the SSL security. This is a different security restriction that is unrelated to the Same Origin Policy.