Home Web Front-end JS Tutorial Use postMessage() to transfer information between iframe cross-domain pages_javascript skills

Use postMessage() to transfer information between iframe cross-domain pages_javascript skills

May 16, 2016 pm 03:07 PM

Due to the restrictions of the web origin policy, when the page uses a cross-domain iframe link, the main page and the sub-page cannot interact, which causes a lot of trouble in the transfer of information between pages. After a series of attempts, Finally I found the following method to achieve it:

1. Pass parameter of sub-page url

To put it simply, add all the parameters that need to be passed to the url that has the same origin as the main page, redirect the sub-page to the url, and then the main page obtains these parameters through the src of the iframe

The process is very complicated and this method is not recommended

2. postMessage()

postMessage() is an event-based message transmission API provided by HTML5, which can realize cross-text document, multi-window, and cross-domain messaging.

postMessage(data,origin) method accepts two parameters

1.data: The data to be passed. The html5 specification mentions that this parameter can be any basic type of JavaScript or a copyable object. However, not all browsers can do this. Some browsers can only Processing string parameters, so we need to use the JSON.stringify() method to serialize object parameters when passing parameters. Similar effects can be achieved by referencing json2.js in lower versions of IE.

2.origin: String parameter, indicating the source of the target window, protocol + host + port number [+URL]. The URL will be ignored, so it does not need to be written. This parameter is for security reasons. The postMessage() method only The message will be passed to the specified window. Of course, if you like, you can also set the parameter to "*", which can be passed to any window. If you want to specify the same origin as the current window, set it to "/".

Send message (subpage)

function sendMessage(param) {
var url;
if (param.url) {
url = param.url;
};
var dataJson = JSON.stringify({     type:1,  
a: param.c, b: param.c,
c: param.c,
url: url
});
window.parent.postMessage(dataJson, '*');
}
Copy after login

Since some browsers can only handle string parameters, we need to use JSON.stringfy() to convert the parameters to strings, and then use JSON.parse() to convert the parameters back to objects when receiving the page.

Receive message

For the parameters passed by the sub-page, we can obtain them by listening to the message event of the window:

window.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
switch (data.type) {
case 1:
alert(data.a);break;
}
}, false); 
Copy after login

The message event has several important attributes

1.data: As the name suggests, it is the message passed in

2.source: the window object that sends the message

3.origin: The source of the message window (protocol + host + port number)

Cross-domain message delivery can be achieved through the postMessage() method and message event. It should be noted that in the demo, we deliver messages to the parent page through the child page, so we use window.parent to send and window to receive. :

window.parent.postMessage(dataJson, '*');

If it is from the homepage to the subpage, it needs to be swapped. Use window to send and window.frames[0] to receive.

The above content is the editor’s introduction to using postMessage() to realize information transfer between iframe cross-domain pages. I hope it will be helpful to everyone!

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles