Chrome消息传递错误:尝试使用断开连接的端口对象

2024-04-28

我的 Chrome 扩展使用长期存在的“端口”对象在“内容脚本”和“弹出”页面之间传递消息。 “弹出窗口”能够向“内容脚本”事件监听器发送消息。但是,“内容脚本”中的“端口”对象无法将消息发送到“弹出”页面。

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 );

    });
});

当执行 '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

我尝试使用“Port”对象和“incomingPort”对象,两者都抛出相同的“错误”。 感觉这与预先创建的“端口”对象的范围有关。

插件代码可在此 git 存储库中找到https://github.com/snambi/chrome_plugin/tree/master/src/chrome https://github.com/snambi/chrome_plugin/tree/master/src/chrome

这个插件有什么问题吗?


我查看了你的代码,这对我来说毫无意义:

  • 你知道港口有一个onMessage and postMessage两边的方法?一个端口足以进行双向通信。
  • 以您的方式在弹出窗口和内容脚本之间进行通信将非常困难。很难同时启动内容脚本和弹出窗口。

由于您的扩展程序没有背景页面,并且内容脚本相对无用,因此我假设您的扩展程序的核心是浏览器操作弹出窗口。您还可以使用以下流程,而不是默认注入内容脚本:

  1. 用户点击浏览器操作
  2. popup.html and popup.js are executed.
    • 添加事件监听器chrome.runtime.onConnect http://code.google.com/chrome/extensions/runtime#event-onConnect,接收端口请求。
    • Use chrome.tabs.query({active:true, windowId:-2}, callback_function); http://code.google.com/chrome/extensions/tabs.html#method-query在当前选项卡中选择当前窗口。 (-2 是chrome.windows.WINDOW_ID_CURRENT http://code.google.com/chrome/extensions/windows.html#property-WINDOW_ID_CURRENT持续的)
    • callback_function接收一个参数:一组选项卡。由于当前窗口不可能没有选项卡,因此选择数组的第一个元素:var tab = tabs[0];
    • 现在,使用chrome.tabs.executeScript(tab.id, {file:'swap.js'}); http://code.google.com/chrome/extensions/tabs.html#method-executeScript执行内容脚本。
    • 在内容脚本中,使用连接到弹出窗口chrome.runtime.connect http://code.google.com/chrome/extensions/runtime#method-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;
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Chrome消息传递错误:尝试使用断开连接的端口对象 的相关文章

随机推荐