JS cross-origin Summary

Source: Internet
Author: User

There are two cross-origin javascript scenarios:
1. subdomains based on the same parent domain, such as a.c.com and B .c.com
2. Based on different parent domains, such as www.a.com and www. B .com
3. different ports, such as www.a.com: 8080 and www.a.com: 8088
4. Different protocols, such as: http://www.a.com and https://www.a.com
For situations 3 and 4, you must use the backend proxy. The specific method is as follows:
A. Create a proxy program in the initiator's domain
B. The initiator's js calls the proxy program in the current domain
C. The proxy sends the request to the receiver and obtains the corresponding data.
D. The proxy returns the obtained data to the initiator's js
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Form id = "form1" runat = "server">
<Div>
<Input type = "text" id = "txtSrc" value = "http://www.gzsums.edu.cn/webclass/html/html_design.html" style = "width: pixel"/>
<Input id = "btnProxy" type = "button" value = "get data through Proxy" onclick = "GetDataFromProxy ();"/> <br/>
<Br/>
<Br/>
</Div>
<Div id = "divData"> </div>
</Form>
</Body>
<Script language = "javascript" type = "text/javascript">
Function GetDataFromProxy (){
Var src = document. getElementById ('txtsrc'). value;
Var request = null;
If (window. XMLHttpRequest ){
Request = new XMLHttpRequest ();
}
Else if (window. ActiveXObject ){
Request = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Request. onreadystatechange = function (){
Var ready = request. readyState;
Var data = null;
{
If (ready = 4 ){
Data = request. responseText;
Document. getElementById ('diddata'). innerHTML = data;
}
Else {
Document. getElementById ('diddata'). text = "Loading ";
}
}
}
Var url = "Proxy. ashx? Src = "+ escape (src );
Request. open ("get", url, false );
Request. send (null );
}
</Script>

The initiator Proxy code is as follows:
Copy codeThe Code is as follows:
Using System. Data;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Xml. Linq;
Using System. IO;
Using System. Net;
Using System. Text;
Namespace WebApplication1
{
/// <Summary>
/// Summary description for $ codebehindclassname $
/// </Summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
Public class Proxy: IHttpHandler
{
Const int BUFFER_SIZE = 8*1024;
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
String src = context. Request ["src"];
WebRequest wr = WebRequest. Create (src );
WebResponse wres = wr. GetResponse ();
Encoding resEncoding = System. Text. Encoding. GetEncoding ("gb2312 ");
StreamReader sr = new StreamReader (wres. GetResponseStream (), resEncoding );
String html = sr. ReadToEnd ();
Sr. Close ();
Wres. Close ();
Context. Response. Write ("<br/> ");
Context. Response. Write (html );
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}

In addition to the background proxy method, situations 1 and 2 can also be solved in seven ways:
1. document. domain + iframe (only solution 1 ):
A. Set document. domain on the initiator and receiver pages, and set the value to the primary domain name of the parent domain (window. location. hostname)
B. Create a hidden iframe on the initiator page. The source of the iframe is the receiver page.
C. Based on the browser, use iframe. contentDocument | iframe.content?#doc ument to obtain the content of the recipient's page.
D. interact with the recipient through the content on the recipient's page.
One disadvantage of this method is that when one domain is attacked, another domain has a security vulnerability.
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Div>
<Input type = "text" id = "txtSrc" value = "http:// B .a.com/DomainTest2.htm" style = "width: pixel"/>
<Input id = "btnDomain" type = "button" value = "get data through Domain" onclick = "GetDataFromDomain ();"/> <br/>
<Br/>
<Br/>
</Div>
<Div id = "divData"> </div>
</Body>
<Script language = "javascript" type = "text/javascript">
Document. domain = 'a. com ';
Var src = document. getElementById ('txtsrc'). value;
Var ifr = document. createElement ('iframe ');
Ifr. src = src;
Ifr. style. display = 'none ';
Document. body. appendChild (ifr );
Function GetDataFromDomain (){
Var doc = ifr. contentDocument | ifr.content##doc ument;
Alert (doc. getElementById ("data"). value );
}
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Input type = "hidden" id = "data" value = "Cross Domain" style = "width: pixel"/>
</Body>
<Script language = "javascript" type = "text/javascript">
Document. domain = 'a. com ';
</Script>

2. dynamically create a script:
A. dynamically load a script on the initiator page. The script URL points to a processing address (backend) of the receiver. The javascript method returned by this address will be executed, in addition, some parameters can be input in the URL. This method only supports the GET method to submit parameters.
B. The loaded script can be processed by itself after calling the cross-origin js method.
The code for the initiator page is as follows:
Copy codeThe Code is as follows:
<Head>
<Title> Script Test </title>
<Script language = "javascript" type = "text/javascript">
Function load_script (callback ){
Var head = document. getElementsByTagName ('head') [0];
Var script = document. createElement ('script ');
Var src = document. getElementById ('txtsrc'). value;
Script. type = 'text/javascript ';
Script. src = src;
// Reference jQuery's script cross-origin method
Script. onload = script. onreadystatechange = function (){
If ((! This. readyState | this. readyState = "loaded" | this. readyState = "complete ")){
Callback & callback ();
// Handle memory leak in IE
Script. onload = script. onreadystatechange = null;
If (head & script. parentNode ){
Head. removeChild (script );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
Head. insertBefore (script, head. firstChild );
}
</Script>
</Head>
<Body>
<Input type = "text" id = "txtSrc" value = "http://www. B .com/scripttest.aspx" style = "width: pixel"/>
<Input type = "button" value = "obtain data by dynamically creating script tags" onclick = "load_script (function () {alert ('script tag loaded successfully ')}) "/>
</Body>

The code of the receiver server is as follows:
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
Response. Clear ();
Response. ContentType = "application/x-javascript ";
Response. Write (String. Format (@ "alert ('{0}');", DateTime. Now ));
Response. End ();
}

3. location. hash + iframe:
A. the initiator creates a hidden iframe. The iframe source points to the recipient's page and transmits data through the hash value of the recipient's page.
B. The initiator creates a timer, regularly checks its location. hash, and processes it accordingly.
C. The receiver creates a hidden iframe. The iframe source points to a proxy page in the domain of the initiator, the data processed by the receiver based on the data imported by the initiator is transmitted through the hash value on the proxy page.
D. The receiver creates a timer, regularly checks its location. hash, and performs corresponding processing.
E. Create a timer on the proxy page, regularly check your location. hash, and synchronously update the hash value of the initiator page.
Www.a.com/a.html#aaa, in which the value of "aaa?location.hash" is
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Div>
<Input type = "text" id = "txtSrc" value = "1" style = "width: pixel"/>
<Input id = "btnAddHash" type = "button" value = "add Hash value" onclick = "addHash ();"/>
<Iframe id = "ifr1" style = "display: none"> </iframe>
</Div>
</Body>
<Script language = "javascript" type = "text/javascript">
Function addHash (){
Var src = document. getElementById ('txtsrc'). value;
If (src. length> 0 ){
ChangeHash (src );
}
}
Function changeHash (src ){
If (document. getElementById ('ifr1 ')){
Var ifr = document. getElementById ('ifr1 ');
Ifr. src = 'HTTP: // www. B .com/test/hashtest2.htmcallback' + src;
}
Else {
Var ifr = document. createElement ('iframe ');
Ifr. setAttribute ('id', 'ifr1 ');
Ifr. src = 'HTTP: // www. B .com/test/hashtest2.htmcallback' + src;
Ifr. style. display = 'none ';
Document. body. appendChild (ifr );
}
}
Function checkHash (){
If (location. hash & location. hash. length> 1 ){
ChangeHash (location. hash. substring (1 ));
}
}
SetInterval (checkHash, 2000 );
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Iframe id = "ifr2" style = "display: none"> </iframe>
</Body>
<Script language = "javascript" type = "text/javascript">
Function checkHash (){
If (location. hash & location. hash. length> 1 ){
Var hashData = location. hash. substring (1 );
Var ifr = null;
If (document. getElementById ('ifr2 ')){
Ifr = document. getElementById ('ifr2 ');
}
Else {
Ifr = document. createElement ('iframe ');
Ifr. setAttribute ('id', 'ifr2 ');
Ifr. style. display = 'none ';
Document. body. appendChild (ifr );
}
Switch (hashData ){
Case '1 ':
Alert ('one ');
If (ifr ){
Ifr. src = 'HTTP: // www.a.com/test/hashtest3.htm%2 ';
}
Break;
Case '2 ':
Alert ('two ');
If (ifr ){
Ifr. src = 'HTTP: // www.a.com/test/hashtest3.htm=1 ';
}
Break;
Default:
Break;
}
}
}
SetInterval (checkHash, 2000 );
</Script>

The proxy Page code for the initiator domain is as follows:
Copy codeThe Code is as follows:
<Body> </body>
<Script language = "javascript" type = "text/javascript">
Function checkHash (){
If (parent & parent. parent & parent. parent. location & self. location. hash. length> 1 ){
Parent. parent. location. hash = self. location. hash. substring (1 );
}
}
SetInterval (checkHash, 500 );
</Script>

4. window. name:
A. Create a hidden iframe on the initiator page and direct the source to the receiver page
B. The receiver puts the data to be transferred in window. name through script on its own page.
C. In the onload method of iframe, the initiator changes the source of iframe to the proxy page in the same domain as itself (because it can only be accessed in the same domain. name value)
D. Obtain the value of window. name (although the iframe source has changed, the value of window. name will not change)
The window. name value can be about 2 MB.
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Div>
<Input id = "btnName" type = "button" value = "get data through window. name" onclick = "getData ();"/>
<Iframe id = "ifr1" style = "display: none" src = "http://www. B .com/Test/NameTest2.htm"> </iframe>
</Div>
</Body>
<Script language = "javascript" type = "text/javascript">
Var ischanged = false;
Function changeSrc (){
If (document. getElementById ('ifr1 ')){
Var ifr = document. getElementById ('ifr1 ');
If (! Ischanged ){
Ischanged = true;
Ifr. contentWindow. location = 'HTTP: // www.a.com/test/nametest3.htm ';
}
Else {
Var data = ifr. contentWindow. name;
Alert (data );
}
}
Else {
Var ifr = document. createElement ('iframe ');
Ifr. setAttribute ('id', 'ifr1 ');
Ifr. src = 'HTTP: // www. B .com/test/nametest2.htm ';
Ifr. style. display = 'none ';
Document. body. appendChild (ifr );
}
}
Function getData (){
SetInterval (Chang ESRC, 2000 );
}
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body> </body>
<Script language = "javascript" type = "text/javascript">
Window. name = 'nametest2 ';
</Script>

The proxy Page code for the initiator domain is as follows:
<Body> </body>
(You don't need to write anything)
5. HTML5 postMessage
A. receiverWindow. postMessage (msg, targetOrigin), receiverWindow is a reference to the window that receives messages. It can be the contentWindow/window of iframe. the return value of open/window. one of the frames; msg is the message to be sent, string type; targetOrigin is used to restrict the uri of the receiverWindow, including the primary domain name and port. "*" indicates no limit, however, to ensure security, you still need to set the settings to prevent messages from being sent to malicious websites. If the URI of targetOrigin does not match the receiverWindow, the system will discard sending messages.
B. The receiver obtains the message through the message event and uses the event. the origin attribute to verify the sender and pass the event. data to obtain the sent message content, event. source to obtain the sender's window object
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Div>
<Input id = "btnPostMessage" type = "button" value = "get data through PostMessage" onclick = "getData ();"/>
<Iframe id = "ifr" style = "display: none" src = "http://www. B .com/Test/PostMessageTest2.htm"> </iframe>
</Div>
</Body>
<Script language = "javascript" type = "text/javascript">
Function getData (){
Var ifr = document. getElementById ('ifr ');
Var targetOrigin = 'HTTP: // www. B .com ';
If (ifr. contentWindow. postMessage ){
Ifr. contentWindow. postMessage ('postmessagetest2', targetOrigin );
}
}
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body> </body>
<Script language = "javascript" type = "text/javascript">
Window. addEventListener ('message', function (event ){
If (event. origin = 'HTTP: // www.a.com '){
Alert (event. data );
Alert (event. source );
}
}, False );
</Script>

6. window. opener (applicable to IE6, 7, namely the operner hack method, but it seems that it is no longer used now. It will be unavailable if you have installed Microsoft's security patch. kb2497640)
A. Create a hidden iframe on the initiator page and direct the source to the receiver page
B. The initiator page uses iframe. contentWindow. opener = {a: function (params ){...}, b: function (params ){...}...} to define the method that can be called by the receiver.
C. The receiver page calls the method defined by the initiator through window. opener. a/window. opener. B.
D. The recipient page uses parent. opener = {c: function (params ){...}, d: function (params ){...}...} to define the method that can be called by the initiator.
E. The initiator page uses opener. c/opener. d to call the method defined by the receiver.
The principle is to reset the opener object.
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Iframe id = "ifr" src = "http://www. B .com/test/OpenerTest2.htm" style = "display: none"> </iframe>
</Body>
<Script language = "javascript" type = "text/javascript">
Var ifr = document. getElementById ('ifr ');
Ifr. contentWindow. opener = {a: function (msg) {alert ('I called method a to get the message:' + msg );}}
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body>
</Body>
<Script language = "javascript" type = "text/javascript">
Window. opener. a ('aaa ');
</Script>

7. window. navigator (applicable to IE6 and 7. It seems to be usable now and has not been patched yet)
A. Create a hidden iframe on the initiator page and direct the source to the receiver page
B. The initiator page goes through window. navigator. a = function (params ){...}; window. navigator. B = function (params ){...}; to define the method called by the receiver
C. The receiver page calls the method defined by the initiator through window. navigator. a (params); window. navigator. B (params );
D. The recipient's page uses window. navigator. c = function (params ){...}; window. navigator. d = function (params ){...}; to define the method called by the initiator.
E. The initiator page calls the method defined by the receiver through window. navigator. c (params); window. navigator. d (params );
The initiator Page code is as follows:
Copy codeThe Code is as follows:
<Body>
<Iframe id = "ifr" src = "http://www. B .com/test/NavigatorTest2.htm" style = "display: none"> </iframe>
</Body>
<Script language = "javascript" type = "text/javascript">
Window. navigator. a = function (msg) {alert ('I have called method a to get the message:' + msg );}
Window. navigator. B = function (msg) {alert ('I have called method B to get the message:' + msg );}
SetInterval (function () {window. navigator. c ('ccc ') ;}, 2000 );
SetInterval (function () {window. navigator. d ('ddd ') ;}, 2000 );
</Script>

The receiver Page code is as follows:
Copy codeThe Code is as follows:
<Body>
</Body>
<Script language = "javascript" type = "text/javascript">
Window. navigator. c = function (msg) {alert ('I have called the c method to get the message:' + msg );}
Window. navigator. d = function (msg) {alert ('I have called the d method to get the message:' + msg );}
SetInterval (function () {window. navigator. a ('aaa') ;}, 2000 );
SetInterval (function () {window. navigator. B ('bbb ') ;}, 2000 );
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.