2013-11-14 18 views
4

我正在使用AngularJS制作Chrome Packaged应用程序,我只是试图从我的后台脚本(“runtime.js”)向另一个脚本发送消息我的项目中的JavaScript文件。Chrome Packaged App - 将消息从background.js传递到另一个脚本页

的manifest.json

{ 
     "name": "App Name", 
     "description": "Chrome Packaged", 
     "version": "0.0.9", 
     "manifest_version": 2, 
     "icons": { 
     "16": "img/icon16.png", 
     "48": "img/icon48.png", 
     "128":"img/icon128.png" 
     }, 
     "app": { 
     "background": { 
      "scripts": ["runtime.js"] 
     } 
     }, 
     "permissions": [ 
     "alarms", 
     "storage", 
     "unlimitedStorage", 
     "notifications", 
     "app.runtime" 
     ] 
    } 

runtime.js

chrome.app.runtime.onLaunched.addListener(function() { 
    chrome.app.window.create('index.html', { 
    minWidth: 400, 
    minHeight: 700, 
    bounds: { 
     width: 1000, 
     height: 700 
    } 
    });  
}); 

chrome.runtime.sendMessage({message: "hello"}, function() { 
    console.log('sent') 
}); 

main.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    console.log('message received!'); 
}); 

我不断收到时我检查的背景页是“端口的错误:莫非不建立连接,接收端不存在。“

任何想法可能是什么问题?谢谢!

+0

我想主要的问题是,我试图让一个后台进程与非后台脚本进行通信。 – adam8810

回答

7

在发送消息之前,您可能只需要等待index.html(我假设它正在使用main.js)加载。但是,您实际上可以通过从chrome.app.window.create返回的窗口对象进行直接函数调用,而不是发送消息。

chrome.app.runtime.onLaunched.addListener(function() { 
    chrome.app.window.create('index.html', { 
     minWidth: 400, 
     minHeight: 700, 
     bounds: { 
      width: 1000, 
      height: 700 
     } 
    }, function (myWindow) { 
     myWindow.contentWindow.addEventListener('load', function(e) { 
      myWindow.contentWindow.functionFromMainJs('hello'); 
     }); 
    });  
}); 
相关问题