我正在开发一个Chrome应用,我正在尝试向外部网页发送消息。在整个场景中,外部网页需要发回消息(但我还没有尝试实现这一点)。
这是我的代码:
background.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prototype</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="background.js"></script>
</body>
</html>
background.js
var FileMessage = "Hello!";
var scriptName = "script.js";
var tabID;
//open a new tab with an app
function openApp() {
var url = "link_to_external_webpage_on_personal_server";
var win = window.open(url);
}
//function to run js files inside the extension
function runScript(script){
chrome.tabs.executeScript(null, {file: script});
}
//function to send a message to all tabs
function sendMessage(){
chrome.tabs.query({'active': true}, function(tabs) {
if(tabs.length === 1){
var tab = tabs[0];
//var tabID = tab.id;
chrome.extension.sendMessage(null, {newMessage : FileMessage});
console.log("extension sent a message...");
}
});
}
//main()
$(document).ready(function() {
openApp();
//when a new tab is updated
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
//createEvent();
sendMessage();
}
});
});
/*function createEvent(){
$.event.trigger({
type: "newMessage",
message: "Hello World!"
});
}*/
外部js文件
$(document).ready(function() {
console.log( "app script is running" );
$(document).on("newMessage", newMessageHandler);
/*document.addEventListener("myEvent",myEventHandler);*/
document.addEventListener("newMessage",myEventHandler);
document.addEventListener('newMessage', function(event) {
console.log("message received...");
}, false);
});
我可以看到大多数代码都是在控制台打印时运行的。我没有收到的唯一一个是“收到的消息”。我也尝试过使用事件(在代码中注释),但我也没有成功。
有谁知道我做错了什么?
提前感谢您的帮助!