javascript chrome 扩展发送响应不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20435528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:29:05  来源:igfitidea点击:

chrome extension send response does not work

javascriptgoogle-chrome

提问by user2922204

I am writing a chrome extension but the send response does not work.

我正在编写 chrome 扩展,但发送响应不起作用。

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {

            if(!request.method){

                    return false;

            }

            if(request.method=='postList' && request.post_list){
                // alert(1);                                                                                                                                                                            
                    a_facebook_api.getPostFromDB(request.post_list, function(data){
                            alert(data);                                                                                                                                                              
                            sendResponse(data);                                                                                                                                                       

                    });

            } else if(request.method=='postAdd' && request.post_data){

                    a_facebook_api.addPostToDB(request.post_data, function(data){

                            sendResponse(data);

                    });

    }

            return true;

}
);

 chrome.runtime.sendMessage({method: "postList",post_list: post_list}, function(response) {

         alert(response);

            });

the function alert data works. It gives me data with JSON format. However, the alert(response) does not show any message. Can anyone give me some ideas why it does not work?

功能警报数据有效。它给了我 JSON 格式的数据。但是,警报(响应)不显示任何消息。谁能给我一些想法为什么它不起作用?

Thank you in advance!

先感谢您!

回答by Josh Cronin

You haven't stated weather you this code is in the content script or the background page. From looking at it I assume it it part of the content script.

你还没有说明天气你这个代码是在内容脚本或背景页面中。从查看它我认为它是内容脚本的一部分。

I tried your code in one of my own extensions and it alerted "[object Object]" which is what happens when you alert a variable that isn't a string or numerical value. If you change the alert data to "response.responseData" it will alert the value you labeled "responseData" from the background page.

我在我自己的一个扩展中尝试了你的代码,它警告了“[object Object]”,这就是当你警告一个不是字符串或数值的变量时会发生的情况。如果您将警报数据更改为“response.responseData”,它将从后台页面提醒您标记为“responseData”的值。

As it wasn't alerting anything for you I think that the script that is listening for the message is not responding properly.

由于它没有为您发出任何警报,我认为正在侦听消息的脚本没有正确响应。

I got the code working. This is the content script:

我让代码工作。这是内容脚本:

//Document ready
window.onload = function() {
    alert('Ready');
    //Send a message
    sendMessage();
}

//Get message from background page
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    //Alert the message
    alert("The message from the background page: " + request.greeting);//You have to choose which part of the response you want to display ie. request.greeting
    //Construct & send a response
    sendResponse({
        response: "Message received"
    });
});

//Send message to background page
function sendMessage() {
    //Construct & send message
    chrome.runtime.sendMessage({
        method: "postList",
        post_list: "ThePostList"
    }, function(response) {
        //Alert the message
        alert("The response from the background page: " + response.response);//You have to choose which part of the response you want to display ie. response.response
    });
}

This is the background script:

这是后台脚本:

//Get message from content script
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        //Alert the message
        alert('The message from the content script: ' + request.method);//You have to choose which part of the response you want to display ie. request.method
        //Construct & send a response
        sendResponse({
            response: "Message received"
        });
    }
);

//Send message to content script
function sendDetails(sendData) {
    //Select tab
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        //Construct & send message
        chrome.tabs.sendMessage(tabs[0].id, {
            greeting: sendData
        }, function(response) {
            //On response alert the response
            alert("The response from the content script: " + response.response);//You have to choose which part of the response you want to display ie. response.response
        });
    });
}

Every time a script receives a message you have to use the "sendResponse" function to send a response.

每次脚本收到消息时,您都必须使用“sendResponse”函数来发送响应。

Hope this helped.

希望这有帮助。

回答by BlackGlory

This same question Chrome Extension Message passing: response not sentwill help.

同样的问题Chrome 扩展消息传递:未发送响应会有所帮助。

You just need to add return trueon listener.

你只需要添加return true监听器。

回答by dikirill

I was looking for the solution to get data from content script inside the popup. Yes, you can have it with storage, but this is applied to all tabs, so better to send message to active tab, and read response:

我正在寻找从弹出窗口内的内容脚本获取数据的解决方案。是的,您可以将其与存储一起使用,但这适用于所有选项卡,因此最好将消息发送到活动选项卡并读取响应:

inside popup.js

在 popup.js 中

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {data: 1}, function (response) {
        console.log(response.data)
    });
});

inside content.js

在 content.js 中

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.data === 1) {
        // accepts only 1 field
        sendResponse({
            data: 2
        });
        // very important to return true 
        return true; 
    }
});