我需要能夠通過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