应用说明:
这个例子演示如何在门户页面以iframe方式嵌入第三方插件,示例中使用了一个来域名下的应用部件,门户页面通过postMessage来通信。iframe中的聊天部件通过父页面标题内容的闪烁来通知用户。不过,由于部件不在父页面中,而是被隔离在一个来之不同源的页面中,所以部件使用postMessage来修改父页面标题!
1、创建门户页面
<!DOCTYPE>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>postMess</title>
<style>
iframe{
width:400px;
height:300px;
}
</style>
<script>
var defaultTitle = 'Portal[http://localhost]';
var sourse = 'http://localhost';
var notificationTimer = null;
function messageHander(e){
if(e.origin == sourse){
notify(e.data);
}else{
//
}
}
function sendString(s){
document.getElementById('wid').contentWindow.postMessage(s,sourse);
}
function notify(message){
stopBinking();
blinkTitle(message,defaultTitle);
}
function stopBinking(){
if(notificationTimer !== null){
clearTimeout(notificationTimer);
}
document.title = defaultTitle;
}
function blinkTitle(m1,m2){
document.title = m1;
notificationTimer = setTimeout(blinkTitle,1000,m2,m1);
}
function sendStatus(){
var statusText = document.getElementById('statusText').value;
sendString(statusText);
}
function loadDemo(){
document.getElementById('sendButton').addEventListener('click',sendStatus,true);
document.getElementById('stopButton').addEventListener('click',stopBinking,true);
sendStatus();
}
window.addEventListener('load',loadDemo,true);
window.addEventListener('message',messageHander,true);
</script>
</head>
<body> Status<input type="text" id="statusText" value="online"/>
<button id="sendButton">change status</button>
<p>
<button id="stopButton">stop Binking title</button>
</p>
<iframe id="wid" src="get.html"><iframe>
</body>
</html>
2、创建聊天部件页面
<!DOCTYPE>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>postMess</title>
<script type="text/javascript">
var sourse = 'http://localhost';
function messageHander(e){
if(e.origin === sourse){
document.getElementById('status').textContent = e.data;
}else{
//
}
}
function sendString(s){
window.top.postMessage(s,sourse);
}
function loadDemo(){
document.getElementById('actionButton').addEventListener('click',function(){
var messText = document.getElementById('messText').value;
sendString(messText);
},true);
}
window.addEventListener('load',loadDemo,true);
window.addEventListener('message',messageHander,true);
</script>
</head>
<body>
status set to:<strong id="status" /></strong>
<div>
<input type="text" id="messText" value="wid nodd" />
<button id="actionButton">send nodd</button>
</div>
</body>
</html>