1 Star 0 Fork 0

megumin/static-pages

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.html 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
megumin 提交于 2018-06-09 16:58 +08:00 . 修复目标链接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>mainWindow</title>
</head>
<body>
<h1>主窗口</h1>
<h3>通过window.open(...)打开另一个隔壁窗口:</h3>
<button id="openNew">打开隔壁窗口</button>
<input type="text" class="send-text">
<button class="send">发送</button>
<div class="content"></div>
<script type="text/javascript" src="../../source/jquery-3.2.1.min.js"></script>
<script>
// 主页面
var $openNew = $('#openNew'); // 打开新窗口的按钮
var $sendText = $('.send-text'); // 发送input内容的按钮
var $content = $('.content'); // 输入文字内容的input
var popup = null; // 目标窗口的引用
// 点击打开新窗口
$openNew.on('click', function() {
popup = window.open('https://sluggishpj.github.io/static-pages/tab-communication/postMessage.html');
setTimeout(function() {
popup.postMessage('连接上了', 'https://sluggishpj.github.io'); // 过4s发送第一条消息
}, 4000);
});
// 点击发送按钮发送
$('.send').click(function() {
var text = $sendText.val();
popup.postMessage(text, 'https://sluggishpj.github.io'); // 发送到上面的新窗口
$('<p>').text('我:' + text).appendTo($content);
$sendText.val('');
});
// 回车发送
$sendText.on('keyup', function(e) {
if (e.keyCode === 13) {
$('.send').click();
}
});
// 处理另一个窗口发送过来的消息
function receiveMsg(event) {
if (event.origin !== 'https://sluggishpj.github.io') { // 判断来源是否符合要求
return;
}
$('<p>').text('对方(' + event.origin + '): ' + event.data).appendTo($content);
}
window.addEventListener('message', receiveMsg, false); // 监听别的窗口发送过来的消息事件
</script>
</body>
</html>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sluggish/staticpages.git
git@gitee.com:sluggish/staticpages.git
sluggish
staticpages
static-pages
master

搜索帮助