In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is web front-end cross-domain". In daily operation, I believe many people have doubts about what web front-end cross-domain is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is web front-end cross-domain?" Next, please follow the editor to study!
1. What is cross-domain?
The word "cross-domain" literally means cross-domain name, but in fact, the scope of cross-domain is definitely more than that narrow. The specific concepts are as follows: as long as there is any difference in protocol, domain name, and port, it is considered to be a different domain. The reason for the cross-domain problem, in fact, it is easy to figure out that if external files are casually referenced and pages under different tags reference similar files to each other, browsers are easily confused and their security is not guaranteed. Everything is safe. However, the security restrictions also bring a lot of trouble to the injection of iframe or ajax applications. So we need to use some methods to enable the js of this domain to manipulate the page objects of other domains or the js of other domains to operate the page objects of this domain (between iframe). The following is a detailed description of the cross-domain situation:
URL indicates whether to allow communication http://www.a.com/a.js http://www.a.com/b.js. Allow http://www.a.com/lab/a.js http://www.a.com/script/b.js under the same domain name. Different folders under the same domain name allow http://www.a.com:8000/a.. Js http://www.a.com/b.js same domain name Different ports do not allow http://www.a.com/a.js https://www.a.com/b.js for the same domain name, and different protocols do not allow http://www.a.com/a.js http://70.32.92.74/b.js domain name and domain name corresponding to ip do not allow http://www.a.com/a.js http://script.a.com/b.js primary domain to be the same. Different subdomains are not allowed (cookie is also not allowed to access) http://www.a.com/a.js http://a.com/b.js the same domain name, different second-level domain names (ditto) are not allowed (cookie is not allowed in this case) http://www.cnblogs.com/a.js http://www.a.com/b.js different domain names are not allowed
Here we need to pay attention to two points:
If it is the protocol and port that cause cross-domain problems, the foreground is powerless.
In the cross-domain problem, the domain is only identified by the "header of URL" rather than trying to determine whether the same ip address corresponds to two domains or whether the two domains are on the same ip. ("the first part of URL" means _ window.location.protocol + _ window.location.host, which can also be understood as "Domains, protocols and ports must match".)
two。 Cross-domain through document.domain
As mentioned earlier, browsers have a same origin policy, and one of the limitations is that documents from different sources cannot be requested through the ajax method. The second limitation is that js cannot be interacted between frames of different domains in the browser. Window objects can be obtained between different frameworks, but the corresponding properties and methods cannot be obtained. For example, there is a page whose address is http://www.damonare.cn/a.html, in which there is an iframe, and its src is http://damonare.cn/b.html,. Obviously, this page is different from the iframe framework in it, so we can't get something in iframe by writing js code in the page:
Function test () {var iframe = document.getElementById ('destroy ifame'); var win = document.contentWindow;// can get the window object in iframe, but the properties and methods of the window object are almost unavailable var doc = win.document;//. Here you can't get the document object var name = win.name;// in iframe, nor can you get the name property of window object}.
At this time, document.domain can come in handy. We just need to set the document.domain of both http://www.damonare.cn/a.html and http://damonare.cn/b.html pages to the same domain name. Note, however, that the setting of document.domain is limited, we can only set document.domain to our own or higher parent domain, and the primary domain must be the same.
Set the document.domain in the page http://www.damonare.cn/a.html:
Document.domain = 'damonare.cn';// is set to the primary domain function test () {alert (document.getElementById (' contacts iframe') .contentWindow); / / contentWindow can get the window object of the child window}
Also set document.domain in the page http://damonare.cn/b.html:
Document.domain = 'damonare.cn';// also sets the document.domain in the iframe load page to make it the same as the document.domain of the main page
The method of modifying document.domain only applies to the interaction between frameworks of different subdomains.
3. Cross-domain through location.hash
Because the parent window can URL read and write to the iframe, iframe can also read and write the URL,URL part of the parent window is called hash, that is, the # sign and its following characters, it is generally used for browser anchor positioning, the server does not care about this part, it should be said that the HTTP request process will not carry hash, so the modification of this part will not produce HTTP requests, but will generate browser history. The principle of this method is to change the hash part of URL for two-way communication. Each window sends a message by changing the location of the other window (since the two pages are not in the same domain, IE and Chrome are not allowed to modify the value of parent.location.hash, so use a proxy iframe under the domain name of the parent window) and receive the message by listening for changes in its own URL. Communication in this way will result in unnecessary browser history, and some browsers do not support onhashchange events and need to poll to know the changes in URL. This also has some disadvantages, such as data is directly exposed in url, data capacity and type are limited, and so on. The following examples are given:
If the parent page is baidu.com/a.html,iframe embedded and the page is google.com/b.html (domain name and other url attributes are omitted here), the communication between the two pages can be achieved through the following methods.
A.html transfers data to b.html
Change the src of iframe to google.com/b.html#paco under a.html
B.html detects changes in url and triggers corresponding actions
B.html sends data to a.html. Since the two pages are not in the same domain, IE and Chrome are not allowed to modify the value of parent.location.hash, so use a proxy iframe under the domain name of the parent window.
Create a hidden iframe under b.html. The src of this iframe is under the baidu.com domain, and hang the hash data to be transferred, such as src= "http://www.baidu.com/proxy.html#data".
Proxy.html monitors changes in url and modifies a.html 's url (because a.html and proxy.html are in the same domain, proxy.html can modify a.html 's url hash)
A.html detects changes in url and triggers corresponding actions
The key code for the b.html page is as follows:
Try {parent.location.hash = 'data';} catch (e) {/ / ie, the security mechanism of chrome cannot be modified parent.location.hash, var ifrproxy = document.createElement (' iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = "http://www.baidu.com/proxy.html#data"; document.body.appendChild (ifrproxy);}
The key code for the proxy.html page is as follows:
/ / because parent.parent (that is, baidu.com/a.html) and baidu.com/proxy.html belong to the same domain, you can change the value of their location.hash parent.parent.location.hash = self.location.hash.substring (1)
4. Cross-domain through HTML5's postMessage method
Advanced browsers Internet Explorer 8, chrome,Firefox, Opera and Safari will all support this feature. This function mainly includes "message" events that receive information and "postMessage" methods that send messages. For example, the A page of damonare.cn domain embeds a B page of google.com domain through iframe, and the communication between An and B can be realized by the following methods
Page A sends a message through the postMessage method:
_ window.onload = function () {var ifr = document.getElementById ('ifr'); var targetOrigin = "http://www.google.com"; ifr.contentWindow.postMessage (' hello worldview, targetOrigin);}
How to use postMessage:
OtherWindow.postMessage (message, targetOrigin)
OtherWindow: the target window, that is, the window to which the message is sent, is a member of the window.frames property or a window created by the window.open method
Message: is the message to be sent with the type of String, Object (not supported by IE8, 9)
TargetOrigin: limit the receiving range of messages. If there is no limit, please use'*
Page B listens for and receives messages through message events:
Var onmessage = function (event) {var data = event.data;// message var origin= event.origin;// source address var source = event.source;// source Window object if (origin== "http://www.baidu.com"){ console.log (data); / / hello world!}}; if (typeof window.addEventListener! = 'undefined') {window.addEventListener (' message', onmessage, false)) } else if (typeof window.attachEvent! = 'undefined') {/ / for ie window.attachEvent (' onmessage', onmessage);}
Similarly, page B can send a message, and then page A listens and receives the message.
5. Cross-domain through jsonp
These just mentioned are two-way communication, that is, two iframe, page and iframe or page and page. Here are several single cross-domain (generally used to obtain data), because the introduction of js through the script tag is not restricted by the same origin policy. So we can introduce a js or a file in the form of another suffix (such as php,jsp, etc.) through the script tag, which returns a call to the js function.
For example, there is an a.html page where the code needs to use ajax to obtain json data on a different domain. Suppose the json data address is http://damonare.cn/data.php, so the code in a.html can do this:
Function dosomething (jsondata) {/ / process the obtained json data}
We see that there is a callback parameter after the address to get the data, which is traditionally used, but it is the same for you to use other parameters. Of course, if you can't control the jsonp address page of the data, you have to follow the format of the party providing the data.
Because it was introduced as a js file, http://damonare.cn/data.php must return an executable js file, so the php code for this page may look like this (be sure to make an agreement with the backend):
In the end, the output result is: dosomething (['axiaqingjingzhongyuanzhongyuanshou])
If your page uses jquery, then it is convenient to do jsonp operations through its encapsulated method.
$.getJSON ('http://example.com/data.php?callback=?,function(jsondata)'){ / / process the json data})
Jquery automatically generates a global function to replace callback=? The question mark in the, which is then automatically destroyed when the data is obtained, actually acts as a temporary proxy function. The $.getJSON method will automatically determine whether to cross-domain, if not, the ordinary ajax method will be called; if cross-domain, the callback function of jsonp will be called in the form of asynchronously loading js files.
Advantages and disadvantages of JSONP
The advantage of JSONP is that it is not limited by the same origin policy as the Ajax request implemented by the XMLHttpRequest object; it is more compatible and can be run in older browsers without the support of XMLHttpRequest or ActiveX; and the result can be returned by calling callback after the request is completed.
The disadvantage of JSONP is that it only supports GET requests but does not support other types of HTTP requests such as POST; it only supports cross-domain HTTP requests and cannot solve the problem of how to call JavaScript between two pages in different domains.
6. Cross-domain through CORS
CORS (Cross-Origin Resource Sharing) cross-domain resource sharing defines how browsers and servers should communicate when cross-domain resources must be accessed. The basic idea behind CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether the request or response should succeed or fail. Currently, all browsers support this feature, and IE browsers cannot be lower than IE10. The whole CORS communication process is automatically completed by the browser and does not require the participation of users. For developers, CORS communication is no different from homologous AJAX communication, and the code is exactly the same. Once the browser finds that the AJAX request is cross-source, it will automatically add some additional header information, and sometimes an additional request, but the user will not feel it.
Therefore, the server is the key to realize CORS communication. As long as the server implements the CORS interface, it can communicate across sources.
A normal ajax request might look like this:
Var xhr = new XMLHttpRequest (); xhr.open ("POST", "/ damonare", true); xhr.send ()
The above damonare section is a relative path. If we are going to use CORS, the relevant Ajax code might be as follows:
Var xhr = new XMLHttpRequest (); xhr.open ("http://segmentfault.com/u/trigkit4/",true); GET", "http://segmentfault.com/u/trigkit4/",true); xhr.send ())
The difference between the code and the previous code is that the relative path is replaced by the absolute path of other domains, that is, the address of the interface you want to access across domains.
The server-side support for CORS is mainly through setting Access-Control-Allow-Origin. If the browser detects the appropriate settings, it can allow Ajax cross-domain access. For more information about CORS, please take a look at teacher Ruan Yifeng's article: detailed explanation of Cross-domain Resource sharing CORS
Comparison between CORS and JSONP
JSONP can only implement GET requests, while CORS supports all types of HTTP requests.
With CORS, developers can use normal XMLHttpRequest to make requests and get data, which has better error handling than JSONP.
JSONP is mainly supported by older browsers, which often do not support CORS, while most modern browsers already support CORS).
Compared with JSONP, CORS is undoubtedly more advanced, convenient and reliable.
7. Cross-domain through window.name
The window object has a name property, which has a feature: in the life cycle of a window (window), all pages loaded by the window share a window.name, each page has read and write access to window.name, window.name is persistent in all pages loaded by a window, and will not be reset because of the loading of the new page.
For example, we enter it on any page
Window.name = "My window's name"; setTimeout (function () {_ window.location.href = "http://damonare.cn/";}, 1000)
After entering the damonare.cn page, we will check and then check the window.name:
Window.name; / / My window's name
As you can see, if you jump to a web page in a tab, our window.name will not change. Based on this idea, we can set the value of window.name on one page and jump to another page. On this page, you can get the window.name we just set up.
For security reasons, browsers always keep window.name as the string type.
This method can also be applied to the interaction with iframe:
For example: my page (http://damonare.cn/index.html) has an embedded iframe:
Window.name is set in iframe.html to be the string we want to pass. We wrote the following code in index.html:
Var iframe = document.getElementById ('iframe'); var data =''; iframe.onload = function () {data = iframe.contentWindow.name;}
Boom! Report a mistake! Sure, because the two pages come from different sources, you can do this to solve this problem:
Var iframe = document.getElementById ('iframe'); var data =''; iframe.onload = function () {iframe.onload = function () {data = iframe.contentWindow.name;} iframe.src = 'about:blank';}
Or replace the about:blank inside with the contents of some homologous page (about:blank,_javascript: and data:, inheriting the source of the page that was loaded into them.)
Compared with the document.domain method, this method relaxes the restriction that the domain name suffix should be the same, and the data of string type can be obtained from any page.
At this point, the study of "what is the cross-domain of the web front end" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.