Js cross-origin and js cross-Origin

Source: Internet
Author: User

Js cross-origin and js cross-Origin

I am so nervous when I write my blog for the first time. I don't know what I can write.

I am sorry for a mistake. Please give me more advice.

1. What is cross-origin?

As long as the Protocol, domain name, and port are any different, it is cross-domain.

For example:

Http://www.example.com Different protocols
Https://www.example.com
Http://www.example.com Different domain names
Http://www.test.com
Http://www.example.com Different ports
Http://www.example.com (81)

 

 

 

 

 

 

Note: The ip address is the same, the domain name is different, and it is also cross-origin. (During local demo writing, the host file is configured with two domain names in 127.0.0.1 to determine whether to calculate cross-domain names. I tried it. Yes)

Ii. Cross-origin type

1. cookie

Only webpages with the same source can share cookies.

2. iframe

The grid Web page is different from the same source and cannot get the DOM of the other side.

3. ajax

Only URLs with the same source can be requested. Otherwise, an error is returned.

Iii. Cross-origin resolution

I configured two domain names in the host file of my computer to simulate cross-domain.

Test1 stands for www.test1.myhost.com; test2 stands for www.test2.myhost.com

1. cookie

In such a case, the cookie can be shared: the first-level domain names of two webpages are the same and the second-level domain names are different. When setting cookies, you can share cookies by specifying that the domain names of the two webpages are the same.

Test1:

document.cookie = 'key1= value1; domain=myhost.com';
console.log(document.cookie);//"key1 = value1"

Test2:

console.log(document.cookie);//"key1 = value1"

They shared cookies, which is terrible.

Open the application and check that the cookie was originally under the myhost.com domain name.

2. iframe

An iframe is nested in a page. The src of this iframe is cross-origin with the home page. In this case, the iframe DOM cannot be obtained on the home page

Test1 is the main page, and test2 is the embedded iframe

To solve the problem of iframe cross-origin, the baby only knows these three types:

(1) segment identifier

(2) window. name

(3) window. postMessage

2.1 segment identifier

It refers to the part after # in the URL. Only the segment identifier is changed and the page is not refreshed.

Implementation ideas:

The parent window can write the data to be transmitted to the src segment identifier of the iframe. iframe is notified by listening to the hashchange event to obtain data.

In the same way, the child window can also change the segment identifier of the parent window to achieve the same effect. Example:

Parent → child:

Home Page

Var origin = $ ('iframe'). attr ('src'); $ ('iframe'). attr ('src', origin + '# Main Window ');

Iframe

Console. log (window. location. hash); // "# Main window"

Child → parent:

Iframe

parent.location.href ='http://www.test1.myhost.com:8080/tutor/cookie#iframe'

Home Page

console.log(window.location.hash);//"#iframe"

2.2 window. name

A browser window has the window. name attribute, which is characterized by setting this attribute for the previous webpage in the same window, regardless of whether the window is the same or not.

Implementation ideas:

Write the data that iframe needs to pass with the home page to the window of iframe. name, and then set the src of iframe to be the same as the home page. At this time, the home page and iframe are the same, and you can get the data of the other side, the changes to the src of iframe do not affect the window. the value of name. The window in iframe can be easily read on the home page. name value, isn't it witty! Let's take another example.

Iframe

Window. name = 'haha, I am iframe'; location. href = 'HTTP: // www.test1.myhost.com: 8080/here is a page with the same source as the home page ';

Home Page

Console. log ($ ('iframe') [0]. contentWindow. name); // "HAHAHA, I am iframe"

2.3 window. postMessage

The new API introduced by html5 allows cross-window communication, regardless of whether the two windows are the same source.

Window. postMessage (data, url); // data is the data to be passed to the target, and the url is the target url.

Note: This window is the target window, not the window of this window.

For example:

Child → parent:

Iframe

top.postMessage('hello', 'http://www.test1.myhost.com:8080/tutor/cookie');

Home Page

window.addEventListener('message', function(e) {  console.log(e.data);//"hello"}, false);

Parent → child:

Home Page

$ ('. Post '). on ('click', function () {$ ('iframe') [0]. contentWindow. postMessage ('Hello hello', 'HTTP: // www.test2.myhost.com: 8080/here is a target url ');});

Iframe

window.addEventListener('message', function(e) {  console.log(e.data);//"hello hello"}, false);

Here, e has several important attributes:

A. data: Passed message

B. source: Window object for sending messages

C. origin: Source of the message sending window (Protocol + host + port number)

3. ajax

Hey, there are also three types of information that the baby knows. Hahaha, that's a coincidence.

(1) JSONP

(2) websocket

(3) CORS

Let's talk about it separately.

JSONP 3.1

The principle is to use script scripts to have cross-origin capabilities.

The basic idea is to add a script element to a webpage and put the requested interface in src, which is not restricted by the same-source policy. After receiving the request, the server puts the data in a specified callback function and transmits it back.

This method is simple and applicable. It is supported by all old browsers, and the server transformation is also very small.

Js implementation:

function addScriptTag(src) {  var script = document.createElement('script');  script.setAttribute("type","text/javascript");  script.src = src;  document.body.appendChild(script);}$('.ajax').on('click', function() {  addScriptTag('http://www.php.myhost.com/jsonp.php?callback=foo');});function foo(data) {  console.log('response data is: ' + data);};

JQuery implementation:

$('.ajax').on('click', function() {  $.ajax({    url: 'http://www.php.myhost.com/jsonp.php',    type: 'get',    dataType: 'jsonp',    jsonpCallback: 'foo',    data: {}  });});function foo(data) {  console.log('Your response is: ' + data);};

PHP code:

<?php$callback = $_GET['callback'];$data = 'hello';echo $callback.'('.json_encode($data).')';?>

3.2 websocket

Websocket is a communication protocol. This Protocol does not implement the same-origin policy. As long as the server supports it, it can be used for cross-source communication.

For example, persistent connection

I don't know much about it, so I won't talk about it first.

3.3 CORS

Getting started

CORS is short for Cross-Origin Resource Sharing. It is W3C standard and is the fundamental solution to cross-source AJAX requests.

CORS requests are divided into two types: simple requests and non-simple requests. There are too many, so I will not introduce them here. I will know it after a query.

A simple request is to add the origin information in the http header when the browser sends a CORS request. The domain contains the protocol name, address, and an optional port to indicate the source of the request. The server determines whether to agree to the request based on this value. (These are all sent by browsers, and developers' Code cannot be reached)

If the specified source is not within the permitted range, the server returns a normal http response. However, the response does not contain the Access-Control-Allow-Origin field. An exception is thrown and the onerror of XMLHttpRequest is captured.

If the specified source is within the permitted range, several additional header information fields (all starting with Access-Contrl-) will be added)

Non-simple requests (the interfaces I normally request are non-simple requests, because the content-type is application/json) are added an http query before the formal communication is initiated, the browser will send a formal XMLHttpRequest request only after a positive response is received asking whether the Domain Name of the current webpage on the server is in the license list. Otherwise, an error is returned.

The pre-check request method is options. The keyword field in the header information is origin, which indicates the source from. After receiving the pre-check request, the server checks the origin and determines whether cross-source requests are allowed to respond.

Allow Request: In an http response, the key is the Access-Control-Allow-Origin field, such as: Access-Control-Allow-Origin: http://api.com, indicating that the http://api.com can request data. If it is set to *, it means that you agree to any cross-origin.

Request not allowed: a normal http response is returned, but there is no CORS header information field. The browser will deem that it does not agree with the pre-check request and trigger an error, which is captured by the onerror of XMLHttpRequest.

All in all, for common cross-Origin requests, you only need to set Access-Control-Allow-Origin on the server side. You do not need to set the front-end. For cookie requests, fields must be set on both the front and back ends. Note that the cookie is the cookie of the domain where the cross-origin request interface is located, rather than the current page.

Check how the front-end cookie request is implemented:

Js

Var xhr = new XMLHttpRequest (); // The front end sets whether xhr. withCredentials = true;

Jquery

$. Ajax ({xhrFields: {withCredentials: true // whether the front-end settings contain cookies },});

Vue:

The vue framework adds the following code to the ajax component encapsulated by vue-resource: Vue. http. options. credentials = true

OK. It's finished ~~~

Oh, by the way, add ajax cross-domain phenomena (these phenomena this blog said very good: http://www.cnblogs.com/dailc/p/5893341.html#crossDomain_crosPrinciple)

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.