Home Web Front-end JS Tutorial Detailed explanation of the principle of cross-domain methods in js_javascript skills

Detailed explanation of the principle of cross-domain methods in js_javascript skills

May 16, 2016 pm 03:49 PM
js Cross domain

Data in the frame (iframe). 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:

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

1. Cross-domain via jsonp

In js, it is not possible to directly use XMLHttpRequest to request data on different domains. 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. 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:

We see that there is a callback parameter after the address to obtain the data. By convention, this parameter name is used, but you can use other parameters as well. 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:

The final output result of that page is:

So the js file obtained through http://example.com/data.php?callback=dosomething is the dosomething function we defined before, and its parameters are the json data we need. In this way we get 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 pass in the json data we need as a parameter. . 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.

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 that in the first method, we said that you cannot use ajax to request documents from different sources. 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 content in the iframe by writing js code in the page:

At this time, document.domain can come in handy. We only need to add http://www.example.com/a.html and http://example.com/ b.htmlJust set the document.domain of these two pages 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

Also set document.domain in the page http://example.com/b.html, and this is also necessary. Although the domain of this document is example.com, it still must be displayed. Set the value of document.domain:

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

But if you want to directly request http://example.com/b.html through ajax in the http://www.example.com/a.html page Page, even if you set the same document.domain, it still won't work, so the method of modifying document.domain is only applicable to the interaction between frames 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, within the life cycle of a window (window), all pages loaded by the window share a window.name, and each page has a unique relationship with the window. name has read and write permissions. window.name is persistent in all pages loaded in a window and will not be reset when a new page is loaded.

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

Look at the code of the b.html page again:

3 seconds after the a.html page was loaded, it jumped to the b.html page, and the result was:

We see that the value set for window.name by its previous page a.html was successfully obtained on the b.html page. 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 even larger, 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. This This is also 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 located on a different domain. The data in /data.html.

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

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:

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 the sake of safety, after obtaining the data, you can Destroy the iframe acting as a proxy. There are many similar ready-made codes on the Internet. If you are interested, you can look for them.

Cross-domain is done through window.name, that’s how it works.

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

The 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 origin or different origins. Currently, IE8, FireFox, Chrome, Browsers such as Opera 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 reception. The domain where the window object of the message is located. If you do not want to limit the domain, you can use the wildcard character *.

The window object that needs to receive messages can obtain the incoming 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 below, with two pages

The result we got after running page a:

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.

Conclusion:

In addition to the above methods, there are also cross-domain methods such as flash and setting up proxy pages on the server, which will not be introduced here.

The above four methods can be selected and applied according to the actual situation of the project. I personally think that the window.name method is not complicated and is compatible with almost all browsers. This is really an excellent cross-domain method.

The above is the entire content of this article, I hope you all like it.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles