【问题标题】:Chrome onMessage not returing valueChrome onMessage 不返回值
【发布时间】:2020-06-18 18:03:04
【问题描述】:

请帮助我理解这一点。 扩展运行良好。没有错误或任何东西。字面上留下吃的回来并运行它。没有任何工作。出现两个错误:

  1. 错误处理响应:TypeError:无法读取未定义的属性“a”:popup.js:21 (setAction)
  2. 未经检查的 runtime.lastError:无法建立连接。接收端不存在。

为了解决问题,我简化了我的代码,以便尝试了解问题所在。

这是我的代码。

popup.js

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('beginSign').addEventListener('click', onBeginClick, false)
    var actionText = document.getElementById('actionText')

    function onBeginClick() {
        chrome.tabs.query({currentWindow: true, active: true},
            function (tabs){
                chrome.tabs.sendMessage(tabs[0].id, {action: "0"}, setAction)
            })
    }


    function setAction(res){
        if(res.a == 0){
            actionText.textContent = "Currently Signing!"
        }
    }
})

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        sendResponse({a: 0})
    }
)

非常感谢任何帮助。

【问题讨论】:

    标签: javascript google-chrome-extension runtime


    【解决方案1】:

    对于错误 1:那么sendResponse 回调函数并不总是返回可靠的值。所以不要使用它。使用另一种方式: 在你的popup.js:

     function onBeginClick() {
            chrome.tabs.query({currentWindow: true, active: true},
                function (tabs){
                    chrome.tabs.sendMessage(tabs[0].id, {action: "0"}, null)
                })
        }
    // set another event listener
    chrome.runtime.onMessage.addListener(request => setAction)
    
    function setAction(res){
            if(res.a == 0){
                actionText.textContent = "Currently Signing!"
            }
        }
    
    

    在你的content.js:

    chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse){
            chrome.runtime.sendMessage({a: 0})
        }
    )
    
    

    对于您的错误 2: 如果你在 chrome 的扩展管理页面中重新加载了你的扩展,你必须重新加载你打开的页面来重新加载内容脚本。

    【讨论】:

    • “sendResponse 回调函数并不总是返回可靠的值” - 这句话真的是错误的,因为它不是真的,切换到单独的 sendMessage 也无济于事。这里实际的潜在问题是,当您在答案末尾解释的那样发送消息时,内容脚本根本没有运行。
    • 如果内容脚本没有错,将是错误2。不是1。
    猜你喜欢
    • 2013-10-18
    • 1970-01-01
    • 2013-10-10
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多