browser restrict cross domain ajax request

2020-08-05 10:22发布

问题:

Why do browser doesn't allow cross-domain AJAX request? Where as a javascript/css file can be retrieved from other domains!!! I know there are ways to solve this, but I want to know what are the factors which made the browsers doesn't allow cross-domain ajax call. More specifically: If any javascript file or css which can be accessed via script or link html tag why it is not accessible via ajax call? Why cross-domain link/script tag is allowed and not ajax?

回答1:

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.