解决思路:利用localStorage跨域的解决方案——postMessage和iframe
- 页面 speak.html 在域A上,页面 iframe.html 在域B上;
- 将 iframe.html 通过 iframe 嵌入到 speak.html;
- 在 iframe.html 页面调用 changeSpeak() 函数触发 speak.html 页面语音开启状态,若开启语音,主页面同时向 iframe.html 页面发送语音文本。
注意:由于项目具体部署路径不同,需根据具体情况修改URL
- speak.html 中
<iframe id="child" src="http://ip:port/pageB/iframe.html"></iframe>
src的值需改为 iframe.html 所在的地址; - iframe.html 中
window.parent.postMessage(isSpeak, 'http://ip:port/');
URL 需改为 speak.html 所在的地址;
主页面,放在域A上
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div style="margin: 10px;">
<div id="speak">page A</div>
</div>
<div>
<iframe id="child" src="http://ip:port/pageB/iframe.html"></iframe>
</div>
<script type="text/javascript">
// 主页面初始化语音讲话状态('0': 关闭, '1':开启)
var speakStatus = '0';
// 主页面监听子页面的message事件,判断当前语音讲话开启状态
window.addEventListener('message', function (e) {
var isSpeak = e.data;
console.log('pageA isSpeak:', isSpeak);
if (isSpeak == '1') {
if (isSpeak != speakStatus) {
// todo: 开启主页面语音讲话
}
window.frames[0].postMessage(JSON.stringify('speak text ' + new Date()), 'http://ip:port/');
} else if (isSpeak == '0') {
if (isSpeak != speakStatus) {
// todo: 关闭主页面语音讲话
}
}
}, false);
</script>
</body>
</html>
子页面,放在域B上
<!doctype html>
<html>
<head>
<style type="text/css">
html,
body {
height: 100%;
margin: 10px;
}
</style>
</head>
<body style="height:100%;">
<p>page B</p>
<button id="container" onclick="changeSpeak();">
click to speak
</button>
<script type="text/javascript">
var isSpeak = '0';
var container = document.getElementById('container');
// iframe接收消息,并把当前讲话状态再次发送给主页面(达到持续接收语音文本的目的)
window.addEventListener('message', function (e) {
if (e.source != window.parent)
return;
console.log('pageB e.data:', e.data);
// todo: 根据主页面传过来的语音文本数据,当前页面做出对应展示
// 暂停 100ms 之后再次发送(当子页面处于开启讲话状态,间隔100ms持续获取主页面的语音文本)
sleep(100);
window.parent.postMessage(isSpeak, 'http://ip:port/');
}, false);
// 点击iframe时触发changeSpeak方法,把变化后的状态发送给主页面
function changeSpeak() {
isSpeak = isSpeak == '0' ? '1' : '0';
window.parent.postMessage(isSpeak, 'http://ip:port/');
}
// 暂停 100ms
function sleep(delay) {
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < delay) {
continue;
}
}
</script>
</body>
</html>