How to implement cross-domain JavaScript

WBOY
Release: 2022-02-08 11:01:39
Original
3327 people have browsed it

Methods for JavaScript to achieve cross-domain: 1. Use jsonp to cross-domain; 2. Use "document.domain" to cross-domain; 3. Use "window.name" to cross-domain; 4. Use "window" .postMessage" method to cross domain.

How to implement cross-domain JavaScript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How does JavaScript achieve cross-domain

The js cross-domain mentioned here refers to data transmission or communication between different domains through js, such as using ajax to request data from a different domain. Or get the data in the frame (iframe) of different domains in the page through js. As long as the protocol, domain name, or port are any different, they are regarded as different domains.

The following table shows the results of homology detection relative to http://store.company.com/dir/page.html:

How to implement cross-domain JavaScript

To be solved For cross-domain issues, we can use the following methods:

1. Cross-domain through jsonp

In js, we directly use XMLHttpRequest to request different domains This is not possible when using data. However, it is possible to introduce js script files from different domains on the page. jsonp uses this feature to achieve it.

For example, there is an a.html page, and the code in it needs to use ajax to obtain json data on a different domain. Assume that the json data address is http://example.com/data.php, then The code in a.html can be like this:

How to implement cross-domain JavaScript

We see that there is a callback parameter after the address to obtain the data. By convention, this parameter name is used, but if you use Same goes for everything else. Of course, if the jsonp address page for obtaining data is not under your control, you must operate in accordance with the format specified by the party that provides the data.

Because it is introduced as a js file, http://example.com/data.php must return an executable js file, so the php code of this page may be like this:

How to implement cross-domain JavaScript

The final output result of that page is:

How to implement cross-domain JavaScript

So through http://example.com/data. The js file obtained by php?callback=dosomething is the dosomething function we defined before, and its parameters are the json data we need, so that we can obtain the data we need across domains.

In this way, the principle of jsonp is very clear. A js file is introduced through the script tag. After the js file is successfully loaded, it will execute the function we specified in the url parameter, and will use the json data we need as Parameters are passed in. Therefore, jsonp requires corresponding cooperation from the server-side page.

After knowing the principle of jsonp cross-domain, we can use js to dynamically generate script tags for cross-domain operations without having to manually write those script tags. If your page uses jquery, you can easily perform jsonp operations through its encapsulated method.

How to implement cross-domain JavaScript

The principle is the same, except that we don’t need to manually insert script tags and define callback functions. jQuery will automatically generate a global function to replace the question mark in callback=?, and then automatically destroy it after obtaining the data. In fact, it acts as a temporary proxy function. The $.getJSON method will automatically determine whether it is cross-domain. If it is not cross-domain, it will call the ordinary ajax method; if it is cross-domain, it will call the jsonp callback function in the form of asynchronously loading the js file.

2. Cross subdomains by modifying document.domain

Browsers all have a same-origin policy, and one of its limitations is what we said in the first method You cannot request documents from different sources through the ajax method. Its second limitation is that js cannot interact between frames in different domains in the browser. One thing that needs to be explained is that different frameworks (father and son or peers) can obtain each other's window objects, but the annoying thing is that you cannot use the properties and methods of the obtained window objects (the postMessage method in HTML5 is an exception, and some browsers such as ie6 can also use a few attributes such as top and parent). In short, you can think of it as only getting an almost useless window object. For example, there is a page whose address is http://www.example.com/a.html. There is an iframe in this page and its src is http://example.com/b.html. Obviously , this page and the iframe inside it are in different domains, so we cannot get the things in the iframe by writing js code in the page:

How to implement cross-domain JavaScript

At this time, document.domain can come in handy. We only need to add the documents of the two pages http://www.example.com/a.html and http://example.com/b.html Just set .domain to the same domain name. But it should be noted that the setting of document.domain is limited. We can only set document.domain to itself or a higher-level parent domain, and the main domain must be the same. For example: the document.domain of a document in a.b.example.com can be set to any one of a.b.example.com, b.example.com, and example.com, but it cannot be set to c.a.b.example.com because this is the current The subdomain of the domain cannot be set to baidu.com because the main domain is no longer the same.

Set document.domain in the page http://www.example.com/a.html:

How to implement cross-domain JavaScript

In the page http://example. Document.domain is also set in com/b.html, and this is also necessary. Although the domain of this document is example.com, the value of document.domain must be set explicitly:

How to implement cross-domain JavaScript

In this way we can access various properties and objects in the iframe through js.

But if you want to directly request the http://example.com/b.html page through ajax in the http://www.example.com/a.html page, even if you set the same document .domain still doesn’t work, so the method of modifying document.domain is only applicable to interactions between frameworks in different subdomains. If you want to interact with pages in different subdomains through the ajax method, in addition to using the jsonp method, you can also use a hidden iframe as a proxy. The principle is to let this iframe load a page in the same domain as the target page you want to get data through ajax, so the page in this iframe can use ajax to get the data you want normally, and then through us The method of modifying document.domain just mentioned allows us to fully control this iframe through js, so that we can let the iframe send an ajax request, and then we can also obtain the received data.

3. Use window.name for cross-domain

The window object has a name attribute, which has a characteristic: that is, in the life of a window (window) During the cycle, all pages loaded by the window share a window.name. Each page has read and write permissions for window.name. Window.name is persisted in all pages loaded by a window. It will not be reset when a new page is loaded.

For example: there is a page a.html, which has this code:

How to implement cross-domain JavaScript

Look at the code of page b.html:

How to implement cross-domain JavaScript

3 seconds after the a.html page is loaded, it jumps to the b.html page. The result is:

How to implement cross-domain JavaScript

Let’s see On the b.html page, the value set for window.name by its previous page a.html was successfully obtained. If window.name is not modified in all subsequent loaded pages, then the value of window.name obtained by all these pages will be the value set by the a.html page. Of course, if necessary, any of the pages can modify the value of window.name. Note that the value of window.name can only be in the form of a string. The maximum size of this string can allow a capacity of about 2M or more, depending on different browsers, but it is generally sufficient.

In the above example, the pages a.html and b.html we used are in the same domain, but even if a.html and b.html are in different domains, the above conclusion is also applicable Yes, this is exactly the principle of using window.name for cross-domain.

Let’s take a look at how to obtain data across domains through window.name. Or give an example.

For example, if there is a www.example.com/a.html page, you need to use the js in the a.html page to get another page www.cnblogs.com/data.html located on a different domain. data.

The code in the data.html page is very simple, it is to set a data value that the a.html page wants to get for the current window.name. Code in data.html:

How to implement cross-domain JavaScript

So in the a.html page, how do we load the data.html page? Obviously we cannot directly load the data.html page by changing the window.location in the a.html page, because we want to get the data in data.html even if the a.html page does not jump. The answer is to use a hidden iframe in the a.html page to act as a middleman. The iframe gets the data from data.html, and then a.html gets the data from the iframe.

If the iframe acting as a middleman wants to obtain the data set by window.name in data.html, it only needs to set the src of this iframe to www.cnblogs.com/data.html. Then if a.html wants to get the data obtained by the iframe, that is, if it wants to get the value of the window.name of the iframe, it must also set the src of the iframe to the same domain as the a.html page. Otherwise, according to the previous Regarding the same-origin policy, a.html cannot access the window.name attribute in the iframe. This is the entire cross-domain process.

Look at the code of the a.html page:

How to implement cross-domain JavaScript

The above code is just the simplest principle demonstration code. You can use js to encapsulate the above process. , such as dynamically creating iframes, dynamically registering various events, etc. Of course, for security reasons, after obtaining the data, you can also destroy the iframe as a proxy. There are many similar ready-made codes on the Internet. If you are interested, you can look for them.

This is how cross-domain is done through window.name.

4. Use the window.postMessage method newly introduced in HTML5 to transmit data across domains.

window.postMessage(message,targetOrigin) method is a newly introduced feature of HTML5 , you can use it to send messages to other window objects, regardless of whether the window object belongs to the same source or different sources. Currently, IE8, FireFox, Chrome, Opera and other browsers already support the window.postMessage method.

The window object calling the postMessage method refers to the window object to receive the message. The first parameter message of this method is the message to be sent, and the type can only be a string; the second parameter targetOrigin is used To limit the domain of the window object that receives the message, if you don’t want to limit the domain, you can use the wildcard *.

The window object that needs to receive the message can obtain the passed message by monitoring its own message event. The message content is stored in the data attribute of the event object.

Sending messages to other window objects mentioned above actually refers to the situation where a page has several frames, because each frame has a window object. When discussing the second method, we said that frameworks in different domains can obtain each other's window objects, and they can also use the window.postMessage method. Let’s look at a simple example with two pages

How to implement cross-domain JavaScript

How to implement cross-domain JavaScript

The result we get after running page a:

How to implement cross-domain JavaScript

We see that page b successfully received the message.

Using postMessage to transmit data across domains is relatively intuitive and convenient, but the disadvantage is that IE6 and IE7 do not support it, so whether to use it or not depends on actual needs.

Related recommendations: javascript learning tutorial

The above is the detailed content of How to implement cross-domain JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!