Home  >  Article  >  Web Front-end  >  Same Origin Policy for JavaScript (Ajax) and Cookies

Same Origin Policy for JavaScript (Ajax) and Cookies

高洛峰
高洛峰Original
2016-11-25 15:21:151377browse

A URL consists of four parts, take www.2cto.com as an example (the default port for http is 80, and the default port for https is 443. If it is the default port, it can be omitted, so this URL is equivalent to www.2cto.com: 80

Protocol: http

Host: www.2cto.com

Port: 80

Path:/

The so-called same origin means that the protocol, host and port of this URL are generally the same. Domain or domain is also the concept of source here.

For the above URL, there are the following results:

Same Origin Policy for JavaScript (Ajax) and Cookies'

There is an exception, javascript can modify the value of the host and port parts by setting document.domain, if In this way, the set value will be used as the standard for same-origin policy check. For example, for http://blog.csdn.net/yanical and http://bbs.csdn.net/, you can execute the following javascript:

[ javascript] document.domain = "csdn.net";

After this, the two pages have the same source. For security reasons, they cannot be set to other main domains, such as http://www.csdn. net/ cannot be set to sina.com

We see that only the host part is set in the javascript, and the port part is not mentioned. In fact, when the above javascript is executed, the port is also set, and is set to a null value. Therefore, if the above javascript is executed for both http://blog.csdn.net:81/yanical and http://blog.csdn.net/yanical, the ports will be set to null. They also become homologous.

The same origin policy was first used to prevent js from one source from obtaining or modifying the document attributes of another source. The source of javascript here refers to the source of the HTML page that loads javascript. Rather than the source where the javascript itself is located.

For example, there are two HTML and two javascript. test.html contains an iframe that references frame.html, and they are in different sources; test.html also references two js, one of them is also different from the source of test.html; the javascript of test.html also tries to modify frame.html

test.html:

[html]








<script> <br/>document.write( '------write from test.html'); <br/>alert(document.getElementById('vFrame').contentDocument.body.innerHTML='------overwrite frame from test.html'; <br/>&lt ;/script> <br/> <br/> <br/>frame.html:<br/> <br/>[html] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <br/><html> <br/> <head> <br/> <br/><body> <br/><script> <br/>document.write('------write from frame.html'); <br/></script>
body>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn