Nam*_*mbi 2 google-chrome google-chrome-extension
我的chrome扩展使用长寿命的"Port"对象在"内容脚本"和"弹出"页面之间传递消息."弹出窗口"能够向"内容脚本"事件监听器发送消息.但是,"内容脚本"中的"端口"对象无法向"弹出"页面发送消息.
var port = chrome.extension.connect({"name":"swap"});
// listener for incoming connections
chrome.extension.onConnect.addListener(function( incomingPort ){
// listener on incoming messages
incomingPort.onMessage.addListener(function( msg ){
if( msg.command === 'get_scripts' ){
//do work
}
var scrs = { 'scripts' : 'name' };
var result = port.postMessage( scrs );
});
});
Run Code Online (Sandbox Code Playgroud)
执行'port.postMessage(Object obj)'时,插件会抛出以下错误,
Error in event handler for 'undefined': Attempting to use a disconnected port object Error: Attempting to use a disconnected port object
at PortImpl.postMessage (miscellaneous_bindings:54:5)
at chrome-extension://loiamkgdhfjdlkcpehnebipeinpcicfj/swap.js:27:31
at [object Object].dispatch (event_bindings:203:41)
at Object.<anonymous> (miscellaneous_bindings:250:22) event_bindings:207
Run Code Online (Sandbox Code Playgroud)
我尝试过使用'Port'对象和'incomingPort'对象,两者都抛出相同的'Error'.感觉它与预先创建的"Port"对象的范围有关.
插件代码可以在这个git存储库中找到https://github.com/snambi/chrome_plugin/tree/master/src/chrome
这个插件有什么问题?
我查看了你的代码,这对我来说没有意义:
onMessage和postMessage两侧的方法?一个端口足以在两个方向上进行通信.由于您的扩展程序没有后台页面和相对无用的内容脚本,我假设您的扩展程序的核心是浏览器操作弹出窗口.您可以使用以下流程,而不是默认注入内容脚本:
popup.html并被popup.js执行.
chrome.runtime.onConnect以接收端口请求.chrome.tabs.query({active:true, windowId:-2}, callback_function);在当前选项卡中选择当前窗口.(-2是chrome.windows.WINDOW_ID_CURRENT常数)callback_function接收一个参数:一组选项卡.由于当前窗口不可能没有制表符,请选择数组的第一个元素:var tab = tabs[0];chrome.tabs.executeScript(tab.id, {file:'swap.js'});执行内容脚本.chrome.runtime.connect.我也看到你port == null用来检查一个端口是否有效.如果这样做,请确保通过在端口断开连接时使变量无效来进行比较:
var port;
chrome.runtime.onConnect.addListener(function(_port) {
// ...optional validation of port.name...
port = _port;
port.onMessage.addListener(function(message) { /* .. logic .. */});
port.onDisconnect.addListener(function() {
port = null;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18681 次 |
| 最近记录: |