Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of JavaScript to implement cross-domain?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge of what JavaScript's cross-domain method is. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's learn about it.

JavaScript cross-domain methods: 1, use jsonp cross-domain; 2, use modified "document.domain" to cross-domain; 3, use "window.name" to cross-domain; 4, use "window.postMessage" method to cross-domain.

The operating environment of this tutorial: windows10 system, javascript1.8.5 version, Dell G3 computer.

How to realize Cross-domain by JavaScript

Js cross-domain refers to data transmission or communication between different domains through js, such as requesting data from a different domain with ajax, or obtaining data from different domains (iframe) in the page through js. As long as there is any difference in protocol, domain name, or port, it is considered to be a different domain.

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

To solve cross-domain problems, we can use the following methods:

1. Cross-domain through jsonp

In js, it is not possible to request data from different domains directly with XMLHttpRequest. However, it is possible to introduce js script files from different domains on the page, and jsonp takes advantage of this feature.

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://example.com/data.php, so the code in a.html can do this:

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://example.com/data.php must return an executable js file, so the php code for this page might look like this:

The final output from that page is:

So the js file we got through http://example.com/data.php?callback=dosomething is the dosomething function we defined earlier, and its parameters are the json data we need, so we get the data we need across domains.

In this way, the principle of jsonp is clear. A js file is introduced through the script tag. When the js file is successfully loaded, the function specified in the url parameter will be executed and the json data we need will be passed in as parameters. Therefore, jsonp needs the corresponding cooperation of the server-side pages.

Once we know the principle of jsonp cross-domain, we can use js to dynamically generate script tags for cross-domain operations, instead of writing those script tags manually. If your page uses jquery, then it is convenient to do jsonp operations through its encapsulated method.

The principle is the same, except that we do not need to manually insert script tags and define fallback functions. 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.

2. Cross subdomains by modifying document.domain

All browsers have a same origin policy, and one of its limitations is that in the first method, we can't request documents from different sources through the ajax method. Its second limitation is that js cannot be interacted between frames of different domains in the browser. It is important to note that different frameworks (parents, sons or peers) can get each other's window objects, but it hurts that you cannot use the properties and methods of the acquired window objects (the postMessage method in html5 is an exception, and some browsers such as ie6 can also use top, parent and a few properties). In short, you can only get an almost useless window object. For example, there is a page whose address is http://www.example.com/a.html, in which there is an iframe, and its src is http://example.com/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:

At this time, document.domain can come in handy. We just need to set the document.domain of both http://www.example.com/a.html and http://example.com/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. 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, example.com, but not c.a.b.example.com, because this is a subdomain of the current domain, nor can it be set to baidu.com, because the main domain is no longer the same.

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

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

This allows us to access various properties and objects in iframe through js.

However, if you want to request the http://example.com/b.html page directly through ajax in the http://www.example.com/a.html page, it will not work even if you set the same document.domain, so the method of modifying document.domain is only applicable to the interaction between frames in different sub-domains. 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 load this iframe into a page in the same domain as the target page where you want to get data through ajax, so the page in this iframe can normally use ajax to get the data you want, and then through the method we just talked about modifying document.domain, so that we can fully control the iframe through js, so that we can let iframe send ajax requests. Then we can also get the data received.

3. Use window.name to cross-domain

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, there is a page a.html with code like this:

Then take a look at the code for the b.html page:

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

We see that we have successfully obtained the value set by its previous page a.html to window.name on the b.html page. If none of the loaded pages have changed the window.name since then, then all of these pages get the value of window.name that the a.html page sets. Of course, any one of these pages can change the value of window.name if necessary. Note that the value of window.name can only be in the form of a string, and the size of this string can allow a capacity of about 2m or more, depending on the browser, but it is generally sufficient.

In the above example, we use pages a.html and b.html in the same domain, but even if a.html and b.html are in different domains, the above conclusion also applies, which is the principle of using window.name to cross-domain.

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

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

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

So how do we load the data.html page into the a.html page? Obviously we can't load the data.html page directly in the a.html page by changing the _ window.location, because we want to get the data in the data.html even if the a.html page doesn't jump. The answer is to use a hidden iframe in the a.html page to act as a middleman, iframe to get the data.html data, and then a.html to get the data obtained by iframe.

If iframe, who acts as a middleman, wants to get the data set by data.html through window.name, all he has to do is set the src of the iframe to www.cnblogs.com/data.html. Then if a.html wants to get the data obtained by iframe, that is, if it wants to get the value of window.name of iframe, it must also set the src of this iframe to the same domain as the a.html page, otherwise, according to the same origin policy mentioned earlier, a.html cannot access the window.name attribute in iframe. This is the whole cross-domain process.

Take a look at the code of the a.html page:

The above code is only the simplest principle demonstration code, you can use js to encapsulate the above process, such as dynamic creation of iframe, dynamic registration of various events, etc., of course, for security, after obtaining the data, you can also destroy the iframe as a proxy. There are many similar off-the-shelf codes on the Internet. If you are interested, you can look for them.

Cross-domain through window.name, this is how it works.

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

The window.postMessage (message,targetOrigin) method is a newly introduced feature of html5, which can be used to send messages to other window objects. No matter whether the window object belongs to the same origin or different sources, browsers such as IE8+, FireFox, Chrome, Opera and so on have supported the window.postMessage method.

The window object that calls the postMessage method refers to the window object to receive the message. The first parameter of this method, message, is the message to be sent, and the type can only be a string. The second parameter, targetOrigin, is used to define the domain of the window object that receives the message. If you do not want to define the domain, you can use the wildcard *.

You need the window object that receives the message, but you get the incoming message by listening to its own message event, and the message content is stored in the data property of the event object.

Sending messages to other window objects above refers to the case where a page has several frames, because each frame has a window object. When discussing the second method, we said that each other's window objects can be obtained between frames of different domains, and the window.postMessage method can also be used. Let's take a look at a simple example with two pages

The result we get after running page a:

We see that the b page successfully received the message.

It is more intuitive and convenient to use postMessage to transfer data across domains, but the disadvantage is that IE6 and IE7 do not support it, so it has to be decided according to the actual needs.

These are all the contents of the article "what is the way for JavaScript to achieve cross-domain?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report