Home > Article > Web Front-end > Practical exercise--js to transfer data between web pages
1. It is estimated that few people know that there is a window.postMessage API in HTML5 APIS. The function of window.postMessage
is to allow programmers to send data information between two windows/frames across domains. Basically, it's like cross-domain AJAX, but instead of interacting between the browser and the server, it communicates between two clients. Let’s take a look at how window.postMessage
works. All browsers except IE6 and IE7 support this feature.
2. First create an index.html file. (When testing, you must use the server to test; file:// The beginning of the address is wrong and access is not allowed to send (because window.postMessage
This method is cross-domain tracking) ajax is almost so very similar))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body,p{ margin: 0px; padding: 0px; } </style> </head> <body> <script> //弹出一个新窗口 var domain = 'http://localhost:8080/chenzhenhua/'; var myPopup = window.open(domain+'lister.html','myWindow');//打开另一个网址 // var array=["100","liyoubing","200"]; var array=[{"姓名":"李友冰"},{"性别":"男"}] //周期性的发送消息 setInterval(function(){ //var message = 'Hello! The time is: ' + (new Date().getTime()); // console.log('blog.local: sending message: ' + message); //array:发送消息de数据,domain: 是url; myPopup.postMessage(array,domain); },6000); </script> </body> </html>
3. The code when creating the lister.html file is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> //监听消息反馈 window.addEventListener('message',function(event) { console.log(event); if(event.origin !== 'http://localhost:8080') return; console.log('received response: ',event.data); },false); </script> </body> </html>
4. The results are as follows:
Related recommendations:
javascript implements the four methods of parameter transfer between html pages
How about html Passing parameters when implementing page jump
The above is the detailed content of Practical exercise--js to transfer data between web pages. For more information, please follow other related articles on the PHP Chinese website!