最近被一个同学问到如何在一个页面点击一个超链接在另一窗口iframe中打开,发现其有点类似百度音乐/QQ音乐在线播放音乐(在一个页面点击播放,另一个页面打开播放)。百度的没看懂,查看QQ音乐发现其利用了localStorage,于是实现了一个demo。
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page A</title>
</head>
<body>
<a href="http://www.baidu.com" class="link">百度一下</a>
<a href="http://www.bootcdn.cn" class="link">bootcdn</a>
<script>
window.onload = function() {
function getStorage() {
try {
return JSON.parse(localStorage.getItem('jsStorage') || '{"opened":false}');
} catch(e) {
return {
opened: false
};
}
}
document.addEventListener('click', function(e) {
var target = e.target,
href;
if (target.className && target.className.indexOf('link') > -1) {
e.preventDefault();
href = target.href;
localStorage.setItem('href', href);
if (!getStorage().opened) {
window.open('b.html');
}
}
}, false);
};
</script>
</body>
</html>
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page B</title>
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
iframe {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe id="targetWin"></iframe>
<script>
window.onload = function() {
// 设置当前页面已被打开
localStorage.setItem('jsStorage', JSON.stringify({
opened: true
}));
var elTargetWin = document.getElementById('targetWin');
function setTargetWin() {
var href = localStorage.getItem('href');
if(href && elTargetWin.src !== href) {
elTargetWin.src = localStorage.getItem('href');
}
}
// 初始化
setTargetWin();
// bad
// setInterval(function() {
// setTargetWin();
// }, 1000);
window.addEventListener('storage', function(e) {
if (e.key === 'href') {
setTargetWin();
}
}, false);
};
window.onbeforeunload = function() {
// 设置当前已被关闭,a.html需重新打开
localStorage.setItem('jsStorage', JSON.stringify({
opened: false
}));
};
</script>
</body>
</html>
要点:
1. localStorage共享数据
2. storage event数据变化监听