Summary of various cross-origin problems in js (1)

Source: Internet
Author: User

Summary of various cross-origin problems in js (1)
What is cross-origin? Why do we need to implement cross-origin? This is because JavaScript does not allow cross-origin calls to objects on other pages for security reasons. That is to say, you can only access resources in the same domain. I think it is necessary to understand the same-source policy in javascript: The same-source policy in javascript. So when we want some specific functions, it is important to implement a reasonable cross-origin request. --> 1. cross-origin of native Ajax object xhr --> 2. simple jsonp --> 3. image Ping --> 4.doc ument. domain + iframe implement native Ajax object XMLHTTPRequest in cross-origin javascript first look at native ajax implementation code: Copy code 1 var xhr = createXHR (); // for IE encapsulate different ajax objects in the browser 2 xhr. onload = function (event) {// make sure to receive the appropriate response 3 if (xhr. status >=200 & xhr. status <300) | xhr. status = 304) {4 alert (xhr. responseText); 5} else {6 alert ('error: '+ xhr. status); 7} 8} 9 xhr. open ('get ','**. php', true); // open party Parameter open (get/post, url, whether to send asynchronous requests) 10 xhr. send (null); // open only starts a request and does not send it. Calling send () will send the request to copy the code. We know that we can send the ajax request by thinking about the above, the response data is automatically filled with the properties of the xhr object, so we can access it. However, there are limitations mentioned above. You can only send requests using the same port and Protocol URL in the same domain. Then the cross-origin issue is solved. Fortunately, there is a thing called CORS (cross-source Resource Sharing). The idea behind it is to use a custom HTTP header to allow the browser to communicate with the server, to determine whether the request or response should succeed or fail. Implementation Method: 1. when sending a get/post request, add an additional Origin header to it, which contains the source information (protocol, domain name, and port) of the Request page ), so that the server determines whether to respond based on the header information, such as: Origin: http://www.nczonline. net2. if the server considers this request acceptable, it sends back the same source information in the header: Access-Control-Allow-Origin: If the http://www.nczonline.net does not have this header or the source information does not match, the server rejects the request. Normally, the browser processes the request. In-depth study of CORS: HTTP access control (CORS). In addition, when it comes to HTTP Headers, I think it is also necessary to understand what parameters are usually used by Request Headers and Response Headers, they will tell us a lot of information: the reason they want to know is that they remember to read this article, and the bearded man used the Date in the response header to implement a countdown: use the Date in the XMLHttpRequest response header to implement countdown JSONP (bidirectional) 1. What is JSONP: jsonp (json with padding)? jsonp looks similar to json, however, jsonp is json contained in function calls. Jsonp consists of two parts: the callback function and the data. The callback function is the function that should be called on the page when the response arrives, and the data is the json data passed into the callback function. He has the following advantages: first, he can directly access the response text; second, jsonp supports bidirectional communication between the browser and the server. But there are also disadvantages: it cannot ensure that the Code loaded from other domains is safe, and it cannot determine whether the jsonp request fails. 2. Usage: dynamically create <script> node: Copy code 1 function handleResponse (response) {2 alert ("your IP address:" + response. ip + ", city where the ip address is located:" + response. city + ", Province:" + response. region_name); 3 4} 5 6 var script = document. createElement ('script'); 7 script. src = 'HTTP: // freegeoip.net/json /? Callback = handleResponse ';/* The http://freegeoip.net is a jsonp location service */8 document. body. insertBefore (script, document. body. firstChild); copy the code, but how to judge whether the script node has been loaded is a problem: ie can only use the readystatechange attribute of the script, and other browsers support the load event of the script. If jquery is used, you don't need to write the above Code. jquery has done a lot of work and calls $. when using the ajax () method, you can encapsulate the parameters if you want to use the jsonp method. For more information, see $. In jQuery. ajax () method using jsonp image ping (one-way) 1. What is image ping: Image ping is a simple, one-way cross-domain communication method with servers, the requested data is sent in the form of a query string, and can be any Content, but it is usually a pixel chart or 204 (No Content ). Image ping has two main drawbacks: first, only get requests can be sent, and second, response text cannot be accessed from the server. 2. Usage: copy the Code 1 var img = new Image (); 2 img. onload = img. onerror = function () {3 alert ("done! "); 4}; 5 img. src = "https://raw.githubusercontent.com/zhangmengxue/Todo-List/master/me.jpg"; 6 document. body. insertBefore (img, document. body. firstChild); copy the code and then the page will show the photos I put somewhere on my github. Similar to , cross-origin embedded resources can also be embedded with: (1) <script src = ""> </script> labels to embed cross-origin scripts. Syntax error messages can only be captured in the same-source script. The above jsonp is also used. (2) <link src = ""> label embedding CSS. Due to the loose Syntax of CSS, a correct Content-Type message header is required for cross-domain CSS. Different browsers have different limits: IE, Firefox, Chrome, Safari (jump to CVE-2010-0051) and Opera. (3) <video> and <audio> embed multimedia resources. (4) <object>, <embed>, and <applet> plug-ins. (5) The font introduced by @ font-face. Some browsers allow cross-origin fonts and some require the same-origin fonts ). (6) Any resources loaded by <frame> and <iframe>. The site can use the X-Frame-Options message header to prevent this form of cross-origin interaction. Document. domain + iframe: The first thing to know about cross-domain implementation is that resources are loaded on the page through <iframe> and cannot be interacted, like the Github Fllow in the About on the Right of my blog, I can only access it. To achieve interaction, document. domain can be used for scenarios with the same primary domain and different subdomains. A.html on www.one.com: copy code 1 document. domain = 'a. com '; 2 var ifr = document. createElement ('iframe'); 3 ifr. src = 'HTTP: // script.a.com/ B .html'; 4 ifr. style. display = 'none'; 5 document. body. appendChild (ifr); 6 ifr. onload = function () {7 var doc = ifr. contentDocument | ifr.content1_doc ument; 8 // click B .html 9 alert (doc. getElementsByTagName ("h1") [0]. childNodes [0]. nodeValue); 10}; copy the code w3w. one. co B .html: document. domain = 'a. com' on m2. In this way, the interaction between page a and page B can be realized. It applies to pages under domain names such as {www.kuqin.com, kuqin.com, script.kuqin.com, and css.kuqin.com}. By default, they use the same protocol and port. Note: The domain of a page is equal to window. location. hostname by default. The primary domain name is a domain name without www, such as a.com. The primary domain name is usually prefixed with a second-level domain name or multi-level domain name. For example, www.a.com is actually a second-level domain name. Domain can only be set as the primary domain name. You cannot set domain to c.a.com in B .a.com. Modify document. when using domain, you also need to pay attention to some problems and the possible impact: modify document. for the possible impact of domain, see here: Summary of cross-origin issues in js document. the domain + iframe section describes document. domain, then I think of other attributes of the document. Let's take a look at this: (1) document. referrer in short, generally, what is the Referer in the Header sent when the browser requests A, then get the document after page. what is the referre value. we can access this attribute of document to know where our page comes from. Some parameters are usually displayed. (2) document. links: it can obtain the href attribute values in all <a> and <area> labels on the page. (3) document. compatMode: If the obtained value is CSS1Compat, it is in standard mode, and BackCompat is in hybrid mode (4) document. the readyState file is loaded with a property value of complete. That is, the file is loaded with full loading. The example above only lists some of them, but there are still many useful ones. You can refer to the manual on your own: document attributes and methods. The second part is to be summarized below: --> 5. use iframe and location. hash --> 6. window. name cross-origin implementation --> 7. HTML5 postMessage implements cross-Origin

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.