postmessage用法详解


当前第2页 返回上一页

test.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<!DOCTYPE html>

<html>

<head>

<title></title>

<meta charset="utf-8"/>

</head>

<body>

<h1 class="header">page B</h1>

  

<input type="text" id="inp" value="我想你">

<button οnclick="send()">send</button>

</body>

  

  

<script>

window.addEventListener('message', function(ev) {

    // if (ev.source !== window.parent) {return;}

    var data = ev.data;

  document.write("my name is ",data);

   document.body.style.background = 'red';

}, false);

  

function send() {

    var data = document.querySelector('#inp').value;

    parent.postMessage(data, 'http://localhost:8080/'); // 若父页面的域名和指定的不一致,则postMessage失败

    // parent.postMessage(data, '*'); // 触发父页面的message事件

}

</script>

</html>

1.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<!DOCTYPE html>

<html>

<head>

<title>window.postMessage</title>

<meta charset="utf-8"/>

<h1>test接收区</h1>

</head>

<body>

  

  

<h1 class="header">page A</h1>

<div class="mb20">

    <textarea name="ta" id="data" cols="30" rows="5">hello world</textarea>

    <button style="font-size:20px;" οnclick="send()">post message</button>

</div>

<!-- 跨域的情况 -->

<iframe src="http://localhost:8080/chajian/test.html" id="child" style="display: block; border: 1px dashed #ccc; height: 300px;"></iframe>

  

<script>

function send() {

    var data = document.querySelector('#data').value;

  

    window.frames[0].postMessage(data, 'http://localhost:8080/'); // 触发跨域子页面的messag事件

}

  

window.addEventListener('message', function(messageEvent) {

    var data = messageEvent.data;

    console.info('message from child:', data);

    document.write("收到了数据: ",data);

    document.body.style.background = 'red';

}, false);

</script>

</body>

</html>

同样的,1.html是主页面。打开html,就可以实现交互了。

更多编程相关学习,请关注php中文网编程入门视频教程频道!

以上就是postmessage用法详解的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

html5中利用postmessage实现ajax中的post跨域

postmessage用法详解

html5跨域信息交互技术之postmessage代码实例详解

详解html5 postmessage解决跨域通信的问题

h5中怎样使用postmessage实现两个网页间传递数据

html5中postmessage api的基本使用

h5里的postmessage api图文详解 详细介绍

如何使用html5中postmessage实现ajax中的post跨域问题的详细介绍

postmessage实现跨域、跨窗口消息传递

html5通过postmessage进行跨域通信的方法

更多相关阅读请进入《postmessage》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...