我需要能够通过web应用程序将Chrome应用程序的postMessage发送到主页并返回。Chrome应用程序和带PostMessage的主页之间的通信
我已经建立了从Chrome应用程序到主页的PostMessage,并且PostMessage也被主页捕获,并且新的发送回来,但是这个PostMessage回复没有被Chrome应用程序捕获。
我可以看到,它有可能在对Chrome浏览器应用程序API:
所以问题是,我不能让Chrome应用可以捕捉到主页的答复,尽管我我使用event.source.postMessage('',event.origin)发送答复。是window.addEventListener('message',messageHandler,false);在background.js结尾处错了?
我必须包括下列:
background.js(其中Chrome应用初始化):
var myAppWin = null;
var webview = null;
chrome.app.runtime.onLaunched.addListener(function() {
// Center window on screen.
var screenWidth = screen.availWidth/2;
var screenHeight = screen.availHeight;
var chromeWindow = chrome.app.window.create('webview-embed.html', {
id: "helloWorldID",
bounds: {
width: screenWidth,
height: screenHeight,
}
}, function(win) {
myAppWin = win;
myAppWin.contentWindow.addEventListener('DOMContentLoaded', function() {
webview = myAppWin.contentWindow.document.getElementById('webview');
try{
webview.addEventListener("contentload", function() {
console.log("webview content is now loaded");
try{
console.log("Trying to post message");
webview.contentWindow.postMessage("Message from Chrome APP!", "*");
}catch(error){
console.log("postMessage error: " + error);
}
});
}
catch(err) {
console.log("Webview error: " + err);
}
});
});
//Event listnener for the PostMessage reply
var messageHandler = function(event) {
console.log("got message from page back: " + event.data);
};
window.addEventListener('message', messageHandler, false);
});
WebView的embed.html与(HTML文件中的我的代码web视图标签)。:
<!DOCTYPE html>
<head>
<title>webview</title>
</head>
<body style='margin:0;padding:0;' >
<webview src="http://localhost" style="width:100%;height:100%;" id="webview" ></webview>
</body>
</html>
的index.html(第e网页上,需要赶上第一PostMessage并发送回应的Chrome应用程序):
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>title</title>
</head>
<body >
<div id="wrapper" >
//body
</div>
//Used to catch messages from the Chrome App and reply back
var messageHandler = function(event) {
console.log('Message received fom APP!');
try{
console.log(event);
event.source.postMessage("Message from page", event.origin);
console.log("Sent massage back to APP");
}catch(error){
console.log("Error on postMessage back to APP" + error);
}
};
window.addEventListener('message', messageHandler, false);
</script>
</body>
</html>
我还没有诊断出整个问题,但其中的一部分可能是您在background.js中使用全局变量来保留数据,而th at不会在事件页面中工作,因为它根据需要被卸载和重新加载。 (只记住设置了某些事件处理程序的事实,但不是处理程序本身。) – 2014-09-20 19:09:18
是否需要从后台页面发送和接收消息?如果您从应用程序的主页面发送消息,它应该可以正常工作,即从webview-embed.html – lazyboy 2014-09-21 03:15:50
的JavaScript中发送它@lazyboy我想做一个[通知](https://developer.chrome.com/apps/notifications)在网页上发生事件(传入消息)时,你知道它是否可以以不同的方式实现吗? – Nederby 2014-09-21 13:00:46