Reputation: 421
Why do browsers disallow cross-domain AJAX requests, while JavaScript/ CSS files can be retrieved from other domains without issue?
I know there are ways to solve this, but I want to know what factors made browsers prevent cross-domain AJAX calls.
If any JavaScript or CSS file can be accessed via <script>
or <link>
tag, why is the same content not accessible via AJAX call? Why are cross-domain link/ script tags allowed and not AJAX?
Upvotes: 0
Views: 625
Reputation: 8415
this is for user safety :
Assume you are logged into Facebook and visit a malicious website in another browser tab. Without the same origin policy JavaScript on that website could do anything to your Facebook account that you are allowed to do. For example read private messages, post status updates, analyse the HTML DOM-tree after you entered your password before submitting the form.
from here
Update :
1- when you target a file using script
or link
or img
tag , you are downloading the file from its server and then its operation is limited to your domain context(access your DOM, manipulate your DOM ...).
2- but when you want to do a ajax call to another website, you potentially have ability to make changes to that website. So to avoid this risk, browser checks your request with the website and gets its response. if it's no
, then browser rejects your request and if it's yes
then it passes
your request to the server.in other hand it's the target website that allows or rejects Cross-Origin Requests.
3- it's not just about Ajax
but also webSocket
or even Flash
.
Upvotes: 3