用 jQuery 封装 postMessage
我正在尝试学习 jQuery,我想制作一个简单的 postMessage 客户端。 可以用jquery封装吗?第一个警报有效,但第二个警报无效。
我正在尝试修改此代码:http://austinchau。 blogspot.com/2008/11/html5-cross-document-messaging.html
$(document).ready(function() {
$('#submit_button').click(function() {
var data = $('#message').val();
window.postMessage('1st' + data);
alert(data);
});
var onmessage = function(e) {
var data = e.data;
var origin = e.origin;
document.getElementById('display').innerHTML = data;
alert('2nd' + data);
};
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}
});
编辑:我知道有 许多插件可用于执行此操作,但我将其作为一个学习过程。
I'm trying to learn jQuery, I want to make a simple postMessage client.
Is it possible to wrap it in jquery? The first alert works, but the second does not.
I'm trying to modify this code: http://austinchau.blogspot.com/2008/11/html5-cross-document-messaging.html
$(document).ready(function() {
$('#submit_button').click(function() {
var data = $('#message').val();
window.postMessage('1st' + data);
alert(data);
});
var onmessage = function(e) {
var data = e.data;
var origin = e.origin;
document.getElementById('display').innerHTML = data;
alert('2nd' + data);
};
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}
});
Edit: I know there are many plugins available to do this, but I'm doing this as a learning process.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
postMessage
用于在不同页面或窗口(或 iframe)之间进行通信。您正在向同一个窗口发布消息。正如您所看到的,什么也没有发生。如果您返回到原始博客文章,作者会创建并显示两个 iframe,然后在它们之间发布消息。
postMessage
is used to communicate between different pages or windows (or iframes). You are posting a message to the same window. As you've seen, nothing happens.If you go back to the original blog post, the author creates and displays two iframes and then posts messages between them.
现在需要 postMessage 的第二个参数。您的代码可以更改为:
其有效,因为您正在发布到自己的窗口。要发布到另一个窗口,请使用以下内容:
进一步阅读:
http://ejohn.org /blog/postmessage-api-changes/
http://dev.w3.org/html5/postmsg/#web-messaging
祝你好运!
The second argument to postMessage is now required. Your code could be changed to this:
Which works because you are posting to your own window. To post to another window, use this:
Further Reading:
http://ejohn.org/blog/postmessage-api-changes/
http://dev.w3.org/html5/postmsg/#web-messaging
Good luck!